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

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

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

Plunkr Demo

最佳答案

或者像这样

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

关于javascript - 将变量的值传递给 angularjs 指令模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20810862/

相关文章:

javascript - 在Vue js中访问父级子事件的数据

javascript - 在 angularjs 中使用 ng-repeat 的表内表

javascript - 如何在 JavaScript 中索引 Prototype 对象

javascript - 如何用 twemoji 替换 html 中的表情符号?

angularjs - 浏览器刷新时错误的基本路径,ngView 中断

angularjs - 如何在 Angularjs 和 Svelte 上创建混合应用程序

javascript - 带变量的 ng-模型名称

javascript - 了解 Ember 中 Controller 和路由之间的关系

angularjs - Angular - 从 Controller 中的对象获取数据到 ng-Model

javascript - $compile 不编译 html 字符串 - angularJs