As a newcomer to AngularJS, I recently attempted the following code:
<div ng-controller="ctrl1">
<div ng-controller="ctrl2">
<select ng-model="myvar" ng-options="c for c in vars" ></select>
<div>{{myvar}}</div>
</div>
</div>
<script src="js/vendor/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myapp", [])
.controller("ctrl1",function($scope, $rootScope) {
$scope.myvar = 1;
$scope.vars = [1, 2, 3];
$scope.$watch("myvar", function(){
console.log("ctrl1 myvar changed");
});
})
.controller("ctrl2",function($scope, $rootScope) {
$scope.$watch("myvar", function(){
console.log("ctrl2 myvar changed");
});
})
.run();
</script>
Upon changing the select value, I noticed that the $watch in ctrl1 was not triggering. However, when I utilized an object in $scope and watched its property, it worked as expected:
<div ng-controller="ctrl1">
<div ng-controller="ctrl2">
<select ng-model="settings.myvar" ng-options="c for c in vars" ></select>
<div>{{settings.myvar}}</div>
</div>
</div>
<script src="js/vendor/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("myapp", [])
.controller("ctrl1",function($scope, $rootScope) {
$scope.settings = {
myvar : 1
};
$scope.vars = [1, 2, 3];
$scope.$watch("settings.myvar", function(){
console.log("ctrl1 myvar changed");
});
})
.controller("ctrl2",function($scope, $rootScope) {
$scope.$watch("settings.myvar", function(){
console.log("ctrl2 myvar changed");
});
})
.run();
</script>
I'm seeking clarification on why this difference exists. What am I missing or failing to comprehend here?