为什么有时候不会触发$ watch listener?

时间:2017-10-26 07:04:10

标签: javascript angularjs watch ng-init

我在我的应用程序中执行以下代码,有时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);
       });
   }

1 个答案:

答案 0 :(得分:1)

不是,根据您的代码,您尚未在任何地方添加 ng-app

<强> DEMO

&#13;
&#13;
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope){

       $scope.$watch("stages", function() {
            alert($scope.stages);
       });
 });
&#13;
<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>
&#13;
&#13;
&#13;