【问题标题】:AngularJS directive not reacting to attribute changeAngularJS 指令对属性更改没有反应
【发布时间】:2013-05-14 12:35:56
【问题描述】:

我有一个聊天指令,用于在页面上放置聊天室。

mod.directive('chat', function () {
  return {
    templateUrl: '/chat',
    replace: true,
    scope: { 
      chatID:'@chat',
    },
    controller: function ($scope, $element, $timeout) {
      var id = $scope.chatID
      ...
    },
    link: function ...
  }
})

HTML 看起来像这样:

<div class="chat" chat="{{currentChatID}}" ui-view="currentChat"></div>
<div class="content" ui-view="mainContent"></div>

这是在一个名为“标准”的文件中

mod.config(function($stateProvider) {
  $stateProvider.state('standard', {
    views: {
      'main': {
        templateUrl: '/tmpl/standard',
        controller: function($scope, $timeout) {
          $scope.currentChatID = ''
          $scope.setCurrentChatID = function(newID) {
            $scope.currentChatID = newID
          }
        }
      }
    }
  })
})

我正在使用 angularjs-ui-router 创建一个父视图,其中包含在该视图内提供聊天的聊天指令。这在第一页加载时工作正常,聊天加载。但是当我更改页面/聊天室时,我使用另一个控制器来运行setCurrentChatID()。这会更改 DOM 中聊天元素的 currentChatID,我还看到聊天元素的属性更改为 angularjs-batarang 中的新 ID,但聊天指令的控制器不运行。当 chatID 发生变化时,如何让它正常工作/激活聊天的控制器?

谢谢。

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angularjs-routing


    【解决方案1】:

    如果没有看到 chat 控制器的其余代码,很难说,但您可能需要在聊天控制器中使用 $watch,例如:

    $scope.$watch('chatID', function(newValue, oldValue) {
        // run some code here whenever chatID changes
    });
    

    编辑:有关$digest 循环和Angular 运行时操作的更多信息,请参阅AngularJS Guide。 (检查运行时部分)

    有关控制器的更多信息,请参阅此AngularJS: Understanding Controllers 指南。以下是与您的问题相关的要点:

    控制器只能用于:

    1. 设置范围对象的初始状态。
    2. 向范围对象添加行为。 (包括创建$watch 等)

    $digest 循环仅处理:

    1. $evalAsync 队列
    2. $watch 列表

    【讨论】:

    • 我只是想知道控制器代码是否应该对摘要做出反应,或者您是否需要为此手动设置手表。如果您需要手表,这是有道理的。
    • 通常情况下,控制器本身应该在每个路由中只运行一次。您想在摘要上运行的任何逻辑都应手动放置在 $watch 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 2015-10-05
    • 2015-06-23
    相关资源
    最近更新 更多