AngularJS | angular.element()函数


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>

输出:
在鼠标进入之前:
元素
鼠标输入后:
元素

示例 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>

输出:
输入前:
元素
输入后:
元素


Made with ❤️ in Chengdu. Copyright reserved 2019-2022.

蜀ICP备20006366号-1