1
從父視圖更新$state.current.data
時,我無法觸發$scope.$watch
或$scope.$watchCollection
。爲什麼當父親改變UI路由器狀態數據時觀察者不會觸發?
我已經創建了一個運動員來演示: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;
}
])
啊,謝謝!我忘記了在'$ watch'命令中引用對象名稱的引號。 – adamweeks
我想知道這可以如何工作(無論如何,它不在這裏)。 $狀態不在範圍內!爲了使它工作,我必須定義一個函數,返回要觀看的數據,然後觀察函數結果。 –