角度指令的参数相同

Arguments are same for angular directive

本文关键字:参数 指令      更新时间:2024-02-01

我有以下指令:

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