當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


AngularJS angular.element()用法及代碼示例


AngularJS中的angular.element()函數用於將DOM元素或HTML字符串初始化為jQuery元素。如果jQuery可用,則angular.element可以用作jQuery函數的別名,也可以用作將元素或字符串包裝在Angular的jqlite中的函數。

用法:

angular.element(element)

其中element是指HTML DOM元素或要包裝到jQuery中的字符串。


示例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> 
    </script> 
    <title> 
      angular.element() 
  </title> 
</head> 
  
<body ng-app="app"> 
    <h1 style="color:green"> 
      GeeksforGeeks 
  </h1> 
    <h2> 
      angular.element() 
  </h2> 
  
    <div ng-controller="geek"> 
        <div ng-mouseenter="style()"
             id="ide" 
             ng-mouseleave="remove()"> 
            {{name}} 
        </div> 
    </div> 
    <script> 
        var app = angular.module("app", []); 
        app.controller('geek', ['$scope', '$document', 
            function($scope, $document) { 
                $scope.name = "GeeksforGeeks"; 
                
                $scope.style = function() { 
                 angular.element( 
                   $document[0].querySelector('#ide')).css({ 
                        'color':'white', 
                        'background-color':'green', 
                        'width':'200px' 
                    }); 
                }; 
                $scope.remove = function() { 
                 angular.element( 
                   $document[0].querySelector('#ide')).css({ 
                        'color':'black', 
                        'background-color':'white' 
                    }); 
                }; 
            } 
        ]); 
    </script> 
  
</body> 
  
</html>

輸出:
在Mouseenter之前:
element
在mouseenter之後:
element

示例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> 
    </script> 
    <title> 
      angular.element() 
  </title> 
</head> 
  
<body ng-app="app" 
      style="text-align:Center"> 
    <h1 style="color:green"> 
      GeeksforGeeks 
  </h1> 
    <h2> 
      angular.element() 
  </h2> 
    <div ng-controller="geek"> 
        <input type="text" 
               id="text" 
               ng-model="myVal" /> 
        
        <button ng-click="getVal()"> 
          Click me! 
      </button> 
        <br /> 
        <br><b>You typed:</b> {{value}} 
    </div> 
    <script> 
        var app = angular.module("app", []); 
        app.controller('geek', ['$scope',  
           '$document', function($scope, $document) { 
                $scope.myVal = ""; 
                $scope.getVal = function() { 
                  $scope.value = angular.element( 
                    $document[0].querySelector( 
                      '#text')).val(); 
            } 
        }]); 
    </script> 
</body> 
  
</html>

輸出:
輸入之前:
element
輸入後:
element



相關用法


注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 AngularJS | angular.element() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。