gpt4 book ai didi

javascript - Angular Directive(指令)的参数相同

转载 作者:行者123 更新时间:2023-12-02 14:47:49 24 4
gpt4 key购买 nike

我有以下指令:

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>

问题是它们的id(因此,{{type}})变得相同(最后一个,TYPE3),尽管我发送不同的类型值(也可以在 console.log(attrs) 中看到)。

这有什么问题吗?

最佳答案

您需要为指令设置隔离范围,这样它就不会影响外部范围:

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"];
}
};
});

Best Practice: Use the scope option to create isolate scopes when making components that you want to reuse throughout your app.

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

关于javascript - Angular Directive(指令)的参数相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445662/

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