传递一个变量的值angularjs指令模板函数 [英] Passing value of a variable to angularjs directive template function

查看:164
本文介绍了传递一个变量的值angularjs指令模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个$范围的变量传递给一个指令,但它不工作。我赶上了变量模板函数:

I am trying to pass a $scope's variable to a directive, but its not working. I am catching the variable in the template function:

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

我需要的是变量 filterby 不是变量名本身的价值。

What I need is the value of variable filterby not the variable name itself.

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

<一个href=\"http://plnkr.co/edit/yPopi0mYdViElCKrQAq9?p=$p$pview\">http://plnkr.co/edit/yPopi0mYdViElCKrQAq9?p=$p$pview

这篇关于传递一个变量的值angularjs指令模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆