When working with an AngularJS controller, I set some variables on the server side using ng-init
.
/* Setting variables in server side View */
<div ng-controller="myController" ng-init="myFoo=@myFoo;myBar=@myBar">...</div>
/* Controller logic in myApp.js */
app.Controller("myController", function(){
// Ensure myFoo and myBar are initialized before proceeding
$scope.$watch("myFoo", function(n,o){}); //?
$scope.$watch("myBar", function(n,o){}); //?
// Perform actions dependent on myFoo and myBar values
for(i=0; i<myFoo; i++) { console.log(myBar); }
});
The key is to ensure that the for
loop is only executed once the myFoo
and myBar
variables are initialized.
Is there a way to achieve this without resorting to unconventional methods like using $timeout
?
Here is a link to a CodePen for reference.
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+" to "+n+"; >"+$scope.myFoo);
});
$scope.$watch("myBar", function(n,o){
//$timeout(null,500);
console.log("watch > myBar from: "+o+" to "+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>
When we run the code, we observe the following output:
> Main thread: myFoo is: false
> Main thread: myBar is: false
watch > myFoo from: true to true; >true
watch > myBar from: true to true; >true
It's evident that the main thread accesses the variables before they are initialized, which is not ideal!