gpt4 book ai didi

javascript - angularjs 指令 : how communicate between link and controller?

转载 作者:行者123 更新时间:2023-11-30 12:20:58 24 4
gpt4 key购买 nike

我有一个指令,我需要在我的指令 Controller 中访问其“配置”属性值。由于 Controller 构造函数首先被执行,从 Controller 到链接的通信是可能的,但反之则不然。实现这一目标的最佳方法应该是什么?我考虑过以下方法

1) 将变量添加到范围-在我看来,这会污染作用域,使变量在共享作用域的任何其他地方都可以访问。

2)使用$broadcast再次出现与上述相同的问题

3) 在 Controller 的 this 上传递一个回调函数,并以 config 作为参数从链接函数中调用它

4)通过服务传递值——在我的例子中,我有多个这样的指令需要通过这个服务传递日期

或者是否有更好的方法我错过了这样做?

module.directive('myDirective',function(){

return{
restrict:'E',
templateUrl:'path/to/html',
link:function(scope,iElement,iAttrs,controller){

var config=iAttrs.config;
//How to access this value inside the directive controller?

},
controller:function($scope){
//the directive attribute 'config' is required here for some larger computations which are not
//manipulating the DOM and hence should be seperated from the link function
})

最佳答案

在那里,您可以使用独立作用域概念,在 Controller 中创建独立作用域,并且不会从其父作用域原型(prototype)继承。为此,您需要在指令选项中使用 scope: { ... } 。通过属性在指令内传递范围值有三种选择

  1. @ : 单向绑定(bind)
  2. = : 双向绑定(bind)
  3. & : 表达式

在您的情况下,前两种情况都可以,具体取决于您需要使用哪种情况。如果您只想将范围变量的值传递给指令,在这种情况下,您可以使用第一种方法,即 @ 单向绑定(bind)。

如果你想更新指令和 Controller 中的变量,也就是双向绑定(bind),那么你需要使用 =

我认为 = 适合你的情况,所以你应该选择 =

标记

<my-directive config="config"></my-directive>

指令

app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
config: '='
},
templateUrl: 'path/to/abc.html',
link: function(scope, iElement, iAttrs, controller) {
//here it will be access as scope.config
console.log(scope.config);
},
controller: function($scope) {
console.log($scope.config); //here also it would be available inisde scope
//you could put a watch to detect a changes on config
}
}
});

Demo Plunkr

更新

因为 config 值是从属性提供的,表达式如 {{}} 所以我们可以通过将 [**$在 $attrs 上观察**][2]。为此,您需要在 Controller 上注入(inject) $attrs 依赖项,这将为您提供指令元素上可用的所有属性集合。在同一个 $attrs 对象上,我们将放置 $observe ,它的工作方式与 $watch 相同,它会进行脏检查以及是否值发生变化它触发了那只 watch 。

指令

app.directive('myDirective', function() {
return {
restrict: 'E',
templateUrl: 'path/to/abc.html',
link: function(scope, iElement, iAttrs, controller) {
//here it will be access as scope.config
console.log(scope.config);
},
controller: function($scope,$attrs) {
//you could put a watch to detect a changes on config
$attrs.$observe('config', function(newV){
console.log(newV);
})
}
}
});

Updated Demo

关于javascript - angularjs 指令 : how communicate between link and controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31101727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com