angularjs - Why are watchers not firing when ui-router state data is changed on parent? -
i unable $scope.$watch
or $scope.$watchcollection
trigger when updating $state.current.data
parent view.
i've created plunker demonstrate: http://plnkr.co/edit/d4hblq9qvnmolqkxo9jc?p=preview use, navigate /main/1
path , click 'change' button. see $state.data
updated, yet watchers never notification.
here script.js
source:
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 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
looking event value of variable, $state.current.data.hello
. it's doing:
$scope.$watch('hello', function(newobj)...
put variable in quotes , $watch
work expected:
$scope.$watch('$state.current.data.hello', function(newobj)...
Comments
Post a Comment