【问题标题】:Why sometimes doesn't ng-init trigger $watch listener?为什么有时 ng-init 不触发 $watch 监听器?
【发布时间】:2017-10-26 07:04:09
【问题描述】:

我在我的应用程序中执行以下代码,有时 ng-init 不会触发 $watch。有什么想法吗?

HTML

<div ng-controller="MyCtrl">
   <p ng-init="stages = 'coco'">{{x}}</p>
</div>

控制器

var myApp = angular.module('myApp',[]);

   function MyCtrl($scope) {

       $scope.$watch("stages", function() {
            alert($scope.stages);
       });
   }

【问题讨论】:

    标签: javascript angularjs watch ng-init


    【解决方案1】:

    没有,根据您的代码,您没有在任何地方添加 ng-app

    DEMO

    var myApp = angular.module('myApp',[]);
    myApp.controller('MyCtrl',function($scope){
    
           $scope.$watch("stages", function() {
                alert($scope.stages);
           });
     });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="MyCtrl">
       <p ng-init="stages = 'coco'">{{x}}</p>
    </div>

    【讨论】:

    • 对不起,是应用程序代码的一部分。我在应用日志中看到有时候$watch没有触发,有可能吗?。
    • 不,不可能,它总是在变量更改时触发
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2012-12-23
    • 2012-03-19
    相关资源
    最近更新 更多