我试图将$ scope的变量传递给指令,但它不起作用.我在模板函数中捕获变量:
app.directive('customdir', function () { return { restrict: 'E', template: function(element, attrs) { console.log(attrs.filterby); switch (attrs.filterby) { case 'World': return ''; } return ''; } }; });
我需要的是变量的值而filterby
不是变量名本身.
Plunkr演示
或者像这样
app.directive('customdir', function ($compile) { var getTemplate = function(filter) { switch (filter) { case 'World': return '<input type="checkbox" ng-model="filterby">'; default: return '<input type="text" ng-model="filterby" />'; } } return { restrict: 'E', scope: { filterby: "=" }, link: function(scope, element, attrs) { var el = $compile(getTemplate(scope.filterby))(scope); element.replaceWith(el); } }; });
http://plnkr.co/edit/yPopi0mYdViElCKrQAq9?p=preview
模板不应包含逻辑,因为模板是视图.模板应该只包含绑定指令,以根据范围(模型)的更改使视图更新.像这样的东西:
app.directive('customdir', function ($compile) { return { restrict: 'E', scope:{ filterby:"=" }, link:function (scope, element) { scope.$watch("filterby",function(newValue){ //logic is out of template if (newValue == "World"){ scope.showCheckBox = true; } else { scope.showCheckBox = false; } }); }, template: function(element, attrs) { //View should be passive and only listens to changes of model to update it accordingly. return '<input type="checkbox" ng-show="showCheckBox" / ><input type="text" ng-show="!showCheckBox" />'; } }; });
使用此方法,您甚至可以在运行时更改输入,并更新视图以反映更改.
DEMO
如果您想根据某些配置决定使用哪个模板,您应该通过普通属性进行配置,不应该通过范围的属性进行访问.就像这样:
app.directive('customdir', function ($compile) { return { restrict: 'E', scope: { filterby:"=" //filterby is a separate field used for data binding }, template: function(element, attrs) { switch (attrs.type) { //view selection configuration should be obtained from the element case 'checkbox': return '<input type="checkbox">'; } return '<input type="text" />'; } }; });
通过传递正常值来配置它:
<customdir type="checkbox" filterby="name"></customdir>
DEMO