1. 程式人生 > >angularjs系列之run方法操作

angularjs系列之run方法操作

1、$scope.$apply的使用,源生跟angular的結合使用,如果沒有使用$timeout,則使用$scope.$apply,這樣操作$scope下面的變數值的變化,介面上對應的值才會有相應的變化;

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="angular.min.js"></script>
</head>
<body>
  <div ng-controller="Aaa">
    <span>{{name}}</span>
  </div>
  <script>
    var m1 = angular.module('myApp', []);
    m1.controller('Aaa', ['$scope',function($scope) {
      $scope.name = 'Hello aaa';
      
      setTimeout(function() {
        $scope.$apply(function() {//用這個跟第三方庫或者源生一起使用的時候,裡面的變數是可以被監聽到的
          $scope.name = "變變變";
        });
      },5000);
    }]); 
  </script>
</body>
</html>

2、angular.injector(後續再補充);

3、run方法的操作:程式碼如下

run的作用,相當於去初始化一些全域性的資料,省略了控制器的環節,就可以直接把值掛載到全域性作用域下

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="angular.min.js"></script>
</head>
<body>
  <div>
    <span>{{name}}</span>
  </div>
  <script>
    var m1 = angular.module('myApp', []);
    m1.run(['$rootScope','$timeout', function($rootScope, $timeout) {
      $rootScope.name = "pomotodo";
      $timeout(function (){
        $rootScope.name = "變變變";//
      },5000);
    }]);//可以console.log(m1);看看什麼樣的情況
  </script>
</body>
</html>

4、angular.bootstrap方法的使用:動態啟用angular應用

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="angular.min.js"></script>
</head>
<body>
  <!-- <div ng-controller="Aaa">
    <span>{{name}}</span>
  </div> -->
  <!-- <div ng-controller="Bbb">
    <span>{{name}}</span>
  </div> -->
  <div>
    <span>{{name}}</span>
  </div>
  <script>
    var m1 = angular.module('myApp', []);
    m1.run(['$rootScope','$timeout', function($rootScope, $timeout) {
      $rootScope.name = "pomotodo";
      $timeout(function (){
        $rootScope.name = "變變變";
      },5000);
    }]);

    document.onclick = function() {
      angular.bootstrap(document, ['myApp']);
    }
</script> </body> </html>