从父视图更新$scope.$watch
时,我无法触发$scope.$watchCollection
或$state.current.data
。
我创建了一个用来演示的动画:http://plnkr.co/edit/d4hblq9QvnMOLQKxO9jc?p=preview
要使用,请导航至/main/1
路径,然后点击“更改”按钮。您会看到$state.data
已更新,但观察者从未收到通知。
以下是script.js
来源:
var app = angular
.module('MyApp', [
'ui.router'
])
.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/main');
$stateProvider
// States
.state("main", {
data: {hello:'hello'},
controller:'mainController',
url:"/main",
templateUrl: "main_init.html"
})
.state("main.1", {
controller:'childController',
parent: 'main',
url:"/1",
templateUrl: 'form_1.html'
})
}])
.controller('mainController', function ($scope, $state, $timeout) {
$scope.Model = $scope.Model || {Name : "xxx"};
$scope.changeHello = function changeHello(){
console.log('about to change...');
$timeout(function(){
$state.current.data.hello = 'hi';
console.log('changed.');
},3500);
}
})
.controller('childController', function($scope, $state, $timeout){
$scope.changeStatus = 'nothing yet';
$scope.$watch($state.$current.data.hello, function(newObj){
if(newObj){
console.log('changed');
$scope.changeStatus = 'changed via watch';
}
});
$scope.$watchCollection($state.$current.data, function(newObj){
if(newObj){
console.log('changed');
$scope.changeStatus = 'changed via watchcollection';
}
});
$scope.$watchCollection($state.$current, function(newObj){
if(newObj){
console.log('changed');
$scope.changeStatus = 'changed via watchcollection $current';
}
});
$scope.$watchCollection($state.current, function(newObj){
if(newObj){
console.log('changed');
$scope.changeStatus = 'changed via watchcollection current';
}
});
})
app.run(
['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
])
答案 0 :(得分:1)
$watch
正在寻找一个变量值$state.current.data.hello
的事件。这就是它正在做的事情:
$scope.$watch('hello', function(newObj)...
将变量放在引号中,$watch
将按预期工作:
$scope.$watch('$state.current.data.hello', function(newObj)...