angular指令的参数相同

时间:2016-04-06 08:33:25

标签: javascript angularjs angularjs-directive

我有以下指令:

ggplot(toyset) + 
 geom_line(aes(xa, ya), colour="red") + 
 geom_line(aes(xb, yb), colour="green") +
 geom_polygon(data = poly_df,aes(x = x,y = y),fill=poly_df$color)

我在html的不同地方称它为三次:

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>

问题是他们的<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}})虽然我发送了不同的类型值(也见{{1} }})。

这有什么问题?

1 个答案:

答案 0 :(得分:2)

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

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

最佳实践:使用scope选项创建隔离范围   制作要在整个应用中重复使用的组件。

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