2015-04-14 55 views
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; 
     } 
    ]) 

回答

1

$watch正在尋找這是你的變量,$state.current.data.hello的價值的事件。這是它在做什麼:

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

把你的變量,報價和$watch將如預期:

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

+0

啊,謝謝!我忘記了在'$ watch'命令中引用對象名稱的引號。 – adamweeks

+0

我想知道這可以如何工作(無論如何,它不在這裏)。 $狀態不在範圍內!爲了使它工作,我必須定義一個函數,返回要觀看的數據,然後觀察函數結果。 –

相關問題