AngularJS:从父控制器访问指令的隔离范围 [英] AngularJS: Access directive's isolated scope from parent controller

查看:251
本文介绍了AngularJS:从父控制器访问指令的隔离范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写孤立范围的指令,但也想使其可用于父范围的控制器范围。我发现这个解决方案:

I want to write a directive with isolated scope but also want to make that scope available for the parent scope's controller. I found this solution:

<div ng-controller="Main">
  <popupbutton directive-scope="popup"></popupbutton>
</div>

app.directive('popupbutton', [function() {
  return {
    restrict:   "E",
    scope:      {    
      directiveScope: "="
    },
    link:       function(sc, el, attrs) {
      sc.directiveScope = sc;
      sc.testvalue = 'foo';
    }
  };  
}]);

app.controller('Main', function($scope) {
  alert($scope.popup.testvalue);  // Where did the property 'popup' come from?!?
});

请参阅 Plunker

我觉得这有点难看,因为它涉及到编写HTML和控制器中的code你不能告诉其中scope属性是从哪里来的属性。有没有更好的方式来做到这一点?

I find this a bit ugly because it involves writing an attribute in HTML and in controller's code you can't tell where a scope property came from. Is there a better way to do this?

编辑:

此外,它似乎是运行控制器主时$ scope.popup是不可用。尚未执行该指令的链接功能?

Besides, it seems that $scope.popup isn't even available when controller 'Main' is run. The directive's linking function isn't executed yet?

推荐答案

要保持适当的关注分离,你不应该混范围。更何况,这将是很难同步。总结:你的指令不应该知道的任何的有关父作用域(或控制器)和你的控制器不应该知道的任何的有关指令的内部结构。它们是在不同的层分离的组件。

To maintain proper separation of concerns, you should not mix scopes. Not to mention that it will be hard to synchronize. To summarize: your directive should not know anything about the parent scope (or its controller) and your controller should not know anything about a directive's internals. They are separate components in separate layers.

控制器和指令之间进行通信的适当的方式是通过指令属性。在弹出的情况下,也就是说,这可以用一个简单的布尔值进行。

The proper way to communicate between a controller and a directive is through directive attributes. In the case of a popup, say, this can be done with a simple boolean value.

控制器和指令:

app.directive('popupbutton', [function() {
  return {
    restrict: "E",
    scope: { isOpen: "=" },
    template: '<a ng-click="isOpen = !isOpen">Toggle</a><div>Open? {{isOpen}}'
  };
}]);

app.controller('MainCtrl', function($scope) {
  $scope.isOpen = false;
});

和标记:

<popupbutton is-open="isOpen"></popupbutton>

此方法不需要逻辑,开箱,并保持关注清晰分离。这里有一个更新的plunker:<一href=\"http://plnkr.co/edit/otIaGCLmiNdGcYEgi60f?p=$p$pview\">http://plnkr.co/edit/otIaGCLmiNdGcYEgi60f?p=$p$pview

This method requires no logic, works out of the box, and maintains clean separation of concerns. Here's an updated plunker: http://plnkr.co/edit/otIaGCLmiNdGcYEgi60f?p=preview

这篇关于AngularJS:从父控制器访问指令的隔离范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆