评估模板函数中的属性

时间:2014-07-02 10:45:23

标签: angularjs angularjs-directive

我想创建一个使用基于属性值的相应模板的指令。 如果tAttrs.datatypeinput,则加载一个输入元素,如果它是select加载一个select元素。我有一个tmplServer服务,可以提供相应的模板。

基于AngularJS问题(https://github.com/angular/angular.js/issues/7466),我尝试使用$ interpolate服务,但仍然无效!

app.directive('mdmInput', ['$compile', 'tmplServer', '$timeout', '$interpolate', '$rootScope', function($compile, tmplServer, $timeout, $interpolate, $rootScope) {
return {
    restrict: 'C',
    replace: false,
    scope: {
        value: '=',
        datatype: '@',
        finished: '&',
        valueChanged: '&',
        onDelete: '&'
    },
    template: function(tElement, tAttrs){
        return tmplServer.getTemplate($interpolate(tAttrs.datatype)(tElement.parent('.mdm-input').scope()), tAttrs);
    }
};
}]);

现在在tmplServer

getTemplate: function ( datatype, attrs ) {
    console.log(datatype);    // loges an empty string;
    if(datatype === 'select'){
        return selectTmpl;
    } else {
        return inputTmpl;
    }
}

tmplServer.getTemplate: function ( datatype, attrs )中,datatype未被解析。它只是一个空字符串。

有没有办法可以评估模板函数中的属性(在元素附加到DOM之前)?

1 个答案:

答案 0 :(得分:0)

我使用AngularJS 1.3.0-beta.13来重现您的代码。 我测试了以下html:

<select class="mdm-input" datatype="select"></select>
<input type="text" class="mdm-input" datatype="input"/>

我得到以下日志:

   select
   SELECT
   input
   INPUT 

以下是我做的结果:

.directive('mdmInput', ['$compile', '$timeout', '$interpolate', '$rootScope', 'tmplServer', function($compile, $timeout, $interpolate, $rootScope, tmplServer) {
return {
    restrict: 'C',
    replace: false,
    scope: {
        value: '=',
        datatype: '@',
        finished: '&',
        valueChanged: '&',
        onDelete: '&'
    },

    template: function(tElement, tAttrs){
        console.log(tAttrs.datatype);
        console.log(tElement[0].nodeName);
    }
};

了解如何获取元素节点名称以获取大写的SELECT或INPUT,这样可以避免开发人员从自定义属性中指定数据类型(以防万一它可以简化您的用例)。

HTH

相关问题