角度指令的参数相同
Arguments are same for angular directive
我有以下指令:
app.directive('filterComponent', function() {
return {
restrict: 'E',
templateUrl: 'filter-component.html',
link: function(scope, element, attrs) {
console.log(attrs);
scope.type = attrs["type"];
}
};
});
我在我的html:中的不同位置调用了三次
<filter-component type="TYPE1"></filter-component>
<filter-component type="TYPE2"></filter-component>
<filter-component type="TYPE3"></filter-component>
这是指令的html:
<div id="{{type}}" class="filter-container">
<div layout="row" class="rhs-text" ng-show="!noTargetSelectedYet">
<md-input-container flex="">
<label>Search</label>
<input style="position: relative; top: 7.8px;" ng-model="filterText">
</md-input-container>
</div>
</div>
问题是,尽管我为类型发送了不同的值(也见于console.log(attrs)
),但它们的id
(因此,{{type}}
)变得相同(最后一个,TYPE3
)。
这是怎么回事?
您需要为指令设置独立的作用域,这样它就不会影响外部作用域:
app.directive('filterComponent', function() {
return {
restrict: 'E',
scope: {
type: '='
},
templateUrl: 'filter-component.html',
link: function(scope, element, attrs) {
console.log(attrs);
scope.type = attrs["type"];
}
};
});
最佳实践:当制作要在整个应用程序中重复使用的组件。
https://docs.angularjs.org/guide/directive
更新
也要使用filterText
:
app.directive('filterComponent', function() {
return {
restrict: 'E',
scope: {
type: '@', // You want this to be passed as a string
filterText: '=' // You want this to be passed as reference
},
templateUrl: 'filter-component.html',
link: function(scope, element, attrs) {
console.log(attrs);
scope.type = attrs["type"];
}
};
});
HTML:
<filter-component type="TYPE1" filterText="filterText"></filter-component>
为了更好地理解隔离作用域,您可以参考以下内容:http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope
相关文章:
- 参数变量出现ngTable指令问题
- 如何在angularjs中传递对象字段作为指令参数
- 角度指令控制器:参数不是函数,未定义
- 在嵌套递归指令中将参数传递给父控制器方法
- Angularjs将函数从控制器传递到指令(或从指令调用控制器函数)-带参数
- 在更改时选择,插入类似函数的参数或指令之间的差异
- 角度指令的参数相同
- 角度调用父函数,其参数来自两个级别深的指令
- 将对象作为参数传递给指令
- angularjs指令绑定带参数的函数
- 从指令调用控制器函数(使用从指令传递的参数)
- AngularJS 指令参数 “ctrls”
- AngularJS指令接受参数
- 将参数从 html 指令传递到控制器
- 在 TypeScript 中带有函数参数的角度指令
- AngularJS指令范围似乎只接受一个参数
- 如何在指令中获取属性参数
- 参数未在指令函数中传递
- 如何在 AngularJS 中使用属性本身将可写参数传递给属性指令
- 评估指令的参数角度