我是新與AngularJS和我嘗試這樣做:
<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>
當改變選擇的值,在CTRL1 $手錶永遠不會觸發。但是如果我在$ scope中使用一個對象並且觀察它的屬性,它可以工作:
<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>
是否有原因?我在做什麼錯,或者我在這裏聽不懂?