javascriptangularjswatchng-init

Why sometimes doesn't ng-init trigger $watch listener?


I execute the follow code in my app and sometimes ng-init doesn't trigger $watch. Any ideas?

HTML

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

Controller

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

   function MyCtrl($scope) {

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

Solution

  • No it does, according to your code you have not added ng-app anywhere.

    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>