【问题标题】:AngularJS child directive depending on parent directive reusabilityAngularJS 子指令取决于父指令的可重用性
【发布时间】:2015-01-17 11:17:11
【问题描述】:

让我们定义一个简单的场景,其中博客有一个Posts 列表,每个列表都有Comments 和其他Objects。

在构建Post 页面时,我可以定义以下元素:

<post post="post"></post>
<comments post="post"></comments>
<objects post="post"></objects>

或:

<post post="post">
    <comments></comments>
    <objects></objects>
</post>

为了提供可重用性,与元素关联的每个指令都有自己的隔离范围。

然后考虑例如与&lt;comments&gt; 关联的指令,我可以为其提供Add 按钮、Reload comments 按钮等。这很容易,只要它的功能限制在它自己的范围内。

Comments 在Post 首次加载时加载,在与&lt;comments&gt; 关联的指令的link 方法中。当(父)Post 更改时,我如何触发Comments 重新加载?

  1. 在与&lt;comments&gt; 关联的指令中,我是否应该放置一个scope.$watch('post') 以在关联的Post 更改时进行监听并在更改Comments 时触发重新加载?
  2. 我是否应该在Post 指令中创建一个register 函数,其中Comments 和Objects 订阅它们自己的控制器,并在需要重新加载它们时从Post 函数中得到通知?也就是手动实现的观察者模式。
  3. $broadcast$on?不知道如何使用隔离范围来实现它们。

【问题讨论】:

  • 我不确定您在数据方面的架构,但我认为如果您要将 cmets 作为嵌入帖子的对象加载,您的评论指令可以绑定到帖子 cmets 集合并且更改会传播自动添加到您的 UI。编辑:这篇博文很好地解释了umur.io/…

标签: javascript angularjs


【解决方案1】:

我想说的最合适的做法是使用事件。如果范围是隔离的,您可以从指令控制器(或另一个控制器)广播,如此答案:

AngularJS : broadcast event from directive

这里有一些代码演示如何处理隔离范围和事件等:

http://plnkr.co/edit/tpl:rfqcl9AHEoJZEEJxyNn2?p=preview

app.directive('post', function() {
  return {
    scope: {},
    link: function(scope, elem, attrs) {
      console.log('post');
    },
    controller: function($scope) {
      tellComments = function() {
        console.log('telling comments');
        $scope.$broadcast('heyComments');
      };
    },
    template: '<button ng-click="tellComments()">sup</button><div comments></div>'
  };
})

app.directive('comments', function() {
  return {
    scope: {},
    link: function(scope, elem, attrs) {
      console.log('comments');
    },
    controller: function($scope) {
      $scope.$on('heyComments', function() {
        console.log('sup post!');
      });
    }
  }
})

还有模板:

  <body ng-controller="MainCtrl">
    <div post>
      <button ng-click="tellComments()">click me</button>
    </div>
  </body>

因此,单击按钮或执行任何其他调用函数“tellComments”的操作(例如加载一些数据)然后被发送到子指令中,由控制器范围处理 - 与指令范围不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2015-09-24
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多