AngularJS将模型链接到ng-show

时间:2014-02-28 03:17:35

标签: javascript angularjs angularjs-directive

我正在尝试创建一个<input-field>指令,该指令具有基本的表单验证。

我需要标记才能看起来像这样

<div class="form-group has-feedback">
    <input name="street_address_1" ng-model="customer.street_address_1" />
    <span class="fa fa-check fa-fw" ng-show="customerCreateForm.street_address_1.$valid"></span>
    <span class="fa fa-times fa-fw" ng-show="customerCreateForm.street_address_1.$invalid"></span>
</div>

我开始编写该指令,但ng-show属性未正确链接到模型。

myApp.directive('inputField', function() {
    return {
        restrict: 'E',
        scope:{
            fieldName: '@name',
            fieldModel: '=ngModel',
            fieldForm: '=form',
            required: '@'
        },

        replace: true,
        template: '<div class="form-group has-feedback">' +
                  '    <input name="{{ fieldName }}" ng-model="fieldModel" ng-required="required" />' +
                  '    <span class="fa fa-check fa-fw form-control-feedback" ng-show="fieldForm[fieldName][$valid]"></span>' +
                  '</div>'
    }    
});

这就是我使用指令的方式:

<input-field name="street_address_1" ng-model="customer.street_address_1" form="customerCreateForm" required />

修改

这是一个傻瓜:

http://plnkr.co/edit/gVY2BpkqNSKBTHcjteNw?p=preview

1 个答案:

答案 0 :(得分:1)

我认为你需要的是:

ng-show="{{fieldForm.$name}}.{{fieldName}}.$invalid"

它产生:

<span class="fa fa-check fa-fw form-control-feedback ng-hide" 
      ng-show="customerCreateForm.street_address_2.$valid">
</span>

请参阅here