将变量的值传递给angularjs指令模板函数

Vik*_*hal 12 javascript angularjs

我试图将$ scope的变量传递给指令,但它不起作用.我在模板函数中捕获变量:

app.directive('customdir', function () {

    return {
        restrict: 'E',

        template: function(element, attrs) {
            console.log(attrs.filterby);
            switch (attrs.filterby) {
                case 'World':
                    return '<input type="checkbox">';
            }
            return '<input type="text" />';
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

我需要的是变量的值而filterby不是变量名本身.

Plunkr演示

kfi*_*fis 14

或者像这样

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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

http://plnkr.co/edit/yPopi0mYdViElCKrQAq9?p=preview


Kha*_* TO 9

模板不应包含逻辑,因为模板是视图.模板应该只包含绑定指令,以根据范围(模型)的更改使视图更新.像这样的东西:

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"  />'; 
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

使用此方法,您甚至可以在运行时更改输入,并更新视图以反映更改.

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" />';
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

通过传递正常值来配置它:

<customdir type="checkbox" filterby="name"></customdir>
Run Code Online (Sandbox Code Playgroud)

DEMO