AngularJS条件属性(指令)

时间:2014-01-03 15:19:26

标签: angularjs attributes

概念:

<form-field ng-repeat="field in fields" field-model='settings[field.name]'
   {{field.match == undefined && '' || 'field-match="settings[field.match]"'}}>
</form-field>

正如你所看到的,我试图获得条件属性 - 如果设置了field.match - 我想得到:

<form-field field-model='settings[field.name]' field.match="settings[field.match]"></form-field>

否则:

<form-field field-model='settings[field.name]'></form-field>

不幸的是我得到了Error: The string contains invalid characters.

我尝试使用相同的结果(?:)语法,但我发现AngularJS conditionals in HTML Attribute它应该是&amp;&amp; ||语法......我做错了什么?

编辑 这是我的指示:

KPNDirectives.directive("formField", function ($compile) {
  return {
    restrict: 'E',
    replace:true,
    scope: {
      fieldModel : '=', 
      fieldMatch : '=' 
    },
    template:"<div></div>",
    link: function (scope, element, attrs) {
      var type = attrs.fieldType || 'text';
      var requiredAttr = attrs.fieldRequired ? ' required' : ""
      var requiredHelp = ""
      var matchAttr = ""
      var matchHelp = ""
      console.log(attrs);
      if (attrs.hasOwnProperty('fieldMatch')) {
        matchAttr = " password-match=\"fieldMatch\"";
        matchHelp = '<span ng-show="form.'+attrs.fieldName+'.$error.unique">NOT UNIQUE</span>';
      } else {
        matchAttr = ""
        matchHelp = ""
      }
      if (attrs.fieldRequired == "true") {
        var requiredAttr="required"
        var requiredHelp = '<span ng-show="form.'+attrs.fieldName+'.$error.required">REQUIRED</span>';
      } else {
        requiredAttr = ""
        requiredHelp = ""
      }

      var htmlText =  
      '<div class="form-group" ng-form="form" ng-class="{true: \'has-error\', false: \'has-success\'}[form.'+attrs.fieldName+'.$invalid]">'+
      '<label class="control-label col-sm-2" for="'+attrs.fieldName+'">'+attrs.fieldLabel+'</label>'+
      '<div class="col-sm-6">'+ 
      '<input class="form-control" type="'+type+'" placeholder="enter valid name" name="'+attrs.fieldName+'" ng-model="fieldModel" ng-minlength=3 ng-maxlength=20 '+ matchAttr + requiredAttr+'/>'+
      '<span class="help-block">'+
      requiredHelp +
      matchHelp+
      '<span ng-show="form.'+attrs.fieldName+'.$error.minlength">TOO LESS CHARS</span>'+
      '<span ng-show="form.'+attrs.fieldName+'.$error.maxlength">TOO MUCH CHARS</span>'+
      '&nbsp;'+
      '</span>'+
      '</div>'+
      '</div>';
      // console.log(htmlText)
      element.append(htmlText);
      $compile(element.contents())(scope); 
    }
  }
});

1 个答案:

答案 0 :(得分:1)

模板和一般的可解析文本仅在内部属性值(当某些指令使用它们时)或纯文本节点中,由curlies包围。

您可以将您的密码置于field-match地址之内,以获得所需的结果,例如

<form-field ng-repeat="field in fields" field-model='settings[field.name]'
   field-match="{{field.match && settings[field.match]}}">
</form-field>

编辑(在OP添加他的代码之后):

要在属性中插值,请在链接函数中使用attrs.$observe(请参阅ng.$compile.directive.Attributes),而不是在隔离范围定义中链接属性。

attrs.$observe("fieldMatch", function(fieldMatch) {
     $scope.fieldMatch = fieldMatch;
  }
)