当父级更改ui-router状态数据时,为什么观察者不会触发?

时间:2015-04-14 16:08:48

标签: angularjs angular-ui-router

从父视图更新$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;
      }
    ])

1 个答案:

答案 0 :(得分:1)

$watch正在寻找一个变量值$state.current.data.hello的事件。这就是它正在做的事情:

$scope.$watch('hello', function(newObj)...

将变量放在引号中,$watch将按预期工作:

$scope.$watch('$state.current.data.hello', function(newObj)...