$ watch不更新子视图

时间:2016-04-27 13:58:19

标签: angularjs angularjs-watch angularjs-bindings

我有这条指令更改了父$scope.mode中的$scope

angular.module('Selector', []).directive('mySelector', function() {
  var changeMode;
  changeMode = function(newmode) {
    var $scope;
    $scope = this;
    $scope.mode = newmode;
    $('.menu-open').attr('checked', false);
    return $scope.mode;
  };
  return {
    restrict: 'E',
    scope: {
      mode: '=mode',
      id: '@id'
    },
    replace: true,
    templateUrl: './directives/modeSelector/Selector.tpl.html',
    link: function(scope, element, attrs) {
      scope.changeZoneMode = changeMode;
      return scope.$watch((function() {
        return scope.mode;
      }), function(newMode) {
        return scope.mode = newMode;
      });
    }
  };
});

此指令包含在 main.html 中,以及加载子视图的 ui-view

 <my-selector mode="current.Mode" id="{{current.ID}}"></my-selector>
 <!-- This binding works and updates properly -->
 {{current.Mode}}

 <!-- Subview container -->
 <div ui-view="sub"></div>

subviewTemplate.html

<!-- This binding doesn't work! -->
{{current.Mode}}

子视图没有特定的控制器,它使用父视图,如 app.js 中的设置:

.state('app.details', {
  name: 'appDetails',
  url: '/:zoneID',
  views: {
    'appContent': {
      templateUrl: 'main.html',
      controller: 'ctrl'
    }
  }
}).state('app.details.overview', {
  name: 'appDetailsOverview',
  url: '/details',
  views: {
    'appContent': {
      templateUrl: 'main.html',
      controller: 'ctrl'
    },
    'sub': {
      templateUrl: 'subviewTemplate.html',
      controller: 'ctrl'
    }
  }
});

以及 main.html subviewTemplate.html 使用的控制器:

angular.module('myController', ['services']).controller('ctrl', [
  '$scope', 'Data', function($scope, Data) {

    $scope.current = new Data;
    $scope.current.load();

    return $scope.$watch('current.Mode', (function(newValue, oldValue) {
      console.log('Old value is: ' + oldValue);
      $scope.current.Mode = newValue;
      return console.log('new value is: ' + $scope.currentMode);
    }), true);
  }
]);

我不明白为什么它适用于 main.html ,正确更新,但不是 subviewTemplate.html console.log$watch打印正确的值。

有任何帮助吗?我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您正在初始化ctrl控制器的新实例。删除该行,它将使用将是ctrl的父控制器。例如:

'sub': {
    templateUrl: 'subviewTemplate.html'
}
相关问题