将指令属性连接到模板?

时间:2016-11-17 10:23:43

标签: angularjs angularjs-directive

是否有可能使用属性值并使用它在指令模板中连接

<text-input txt-info="textName" ng-model="pi.medRecNumber"> </text-input>

hcare.directive('textInput', function() {
return {
    restrict: 'AE', //attribute or element
    scope: {
        bindedModel: "=ngModel", // Element Model Data
        txtInfo:'@', // Serve as name and id attribute value
    },
    template:
            '<div class="form-group tcell-220" data-ng-class="{true: \'has-error\'}[submitted && formHcare.'+txtInfo+'.$invalid]">'+
                '<div class="fg-line">' +
                    '<input id="'+txtInfo+'" name="'+txtInfo+'" data-ng-model="bindedModel" type="text" class="input-h25 form-control" placeholder="M#####-#"  >'+
                '</div>'+
                '<small class="help-block" data-ng-show="submitted && formHcare.'+txtInfo+'.$error.required">Field Required</small>'+
            '</div>',
    replace: true,
    require: '?ngModel',
    link: function($scope, elem){
        // LOGIC HERE
    }
};

});

1 个答案:

答案 0 :(得分:0)

我想我的工作...... 带有指令的东西是你和父节点具有相同的范围,所以你并不真正需要'bindedModel'变量,你可以像{}}一样使用{{}}来处理txtInfo属性。

以下是我的修补程序代码,以使其正常工作:

hcare.directive('textInput', function() {
  return {
    restrict: 'AE', //attribute or element
    replace: true,
    scope: {
      //bindedModel: "=ngModel", // Element Model Data
      txtInfo:'@', // Serve as name and id attribute value
    },
    template:
    '<div class="form-group tcell-220" data-ng-class="{true: \'has-error\'}[submitted && formHcare.{{txtInfo}}.$invalid]">'+
    '<div class="fg-line">' +
    '<input id="{{txtInfo}}" name="{{txtInfo}}" data-ng-model="pi.medRecNumber" type="text" class="input-h25 form-control" placeholder="M#####-#"  >'+
    '</div>'+
    '<small class="help-block" data-ng-show="submitted && formHcare.{{txtInfo}}.$error.required">Field Required</small>'+
    '</div>',
    //require: '?ngModel',
    link: function($scope, elem){
      // LOGIC HERE
    }
    };
});

不要忘记在控制器中初始化pi对象以使其工作:

hcare.controller('AppCtrl', function($scope) {
  $scope.pi = {};
});

如果您想确保它正常工作,您应该在此输入字段上使用浏览器的inspect元素选项。