javascript - AngularJs watch for all in ng-init -


i initialize variables of angularjs controller on server side using ng-init

/* in server side view */ <div ng-controller="mycontroller" ng-init="myfoo=@myfoo;mybar=@mybar">...</div>  /* in myapp.js */ app.controller("mycontroller", function(){   // wait until myfoo , mybar initialized,    // once defined, perform other tasks    $scope.$watch("myfoo", function(n,o){}); //?   $scope.$watch("mybar", function(n,o){}); //?    // other actions, depending on myfoo , mybar   for(i=0; i<myfoo; i++) { console.log(mybar); } }); 

i need ensure when angularjs reaches for cycle myfoo , mybar variables initialized.

is there way of doing (without using strange things magic=1500 $timeout(magic))?

here codepen

var app = angular.module("myapp", []);  app.controller("myctrl", ['$scope', '$timeout', function($scope, $timeout) {        $scope.myfoo = false;    $scope.mybar = false;        $scope.$watch("myfoo", function(n,o){      //$timeout(null,1500);          console.log("watch > myfoo from: "+o+" "+n+"; >"+$scope.myfoo);    });    $scope.$watch("mybar", function(n,o){      //$timeout(null,500);      console.log("watch > mybar from: "+o+" "+n+"; >"+$scope.mybar);    });        console.log("> main thread: myfoo is: " + $scope.myfoo);    console.log("> main thread: mybar is: " + $scope.mybar);   }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>  <body>    <div ng-app="myapp" ng-controller="myctrl">        <div  ng-init="myfoo=true;mybar=true"></div>  </div>

as can see execution of code

> main thread: myfoo is: false > main thread: mybar is: false watch > myfoo from: true true; >true watch > mybar from: true true; >true 

the main thread reaches variables before initialization... bad !

you can fire function on ng-init.

var app = angular.module("myapp", []);  app.controller("myctrl", ['$scope', '$timeout', function($scope, $timeout) {        $scope.myfoo = false;    $scope.mybar = false;        $scope.$watch("myfoo", function(n,o){      //$timeout(null,1500);          console.log("watch > myfoo from: "+o+" "+n+"; >"+$scope.myfoo);    });        $scope.$watch("mybar", function(n,o){      //$timeout(null,500);      console.log("watch > mybar from: "+o+" "+n+"; >"+$scope.mybar);    });        $scope.load = function(){                   console.log("> main thread: myfoo is: " + $scope.myfoo);          console.log("> main thread: mybar is: " + $scope.mybar);          }       }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>  <body>    <div ng-app="myapp" ng-controller="myctrl">        <div  ng-init="myfoo=true;mybar=true;load()"></div>  </div>


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -