0
votes

I'm using latest version of AngularJS which is 1.2rc3 along with Bootstrap for styling and have directive like this:

angular.module('form.field', [])

.directive('efield', function() {
    return {
        restrict: 'E',
        scope: {
            form: '@',
            fname: '@',
            label: '@'
        },
        template:   "<div data-ng-class=\"{{form}}.{{fname}}.$valid ? 'form-group' : 'form-group has-error'\">" +
                        "<label class='control-label' for='{{fname}}'>{{label}}</label>" +
                        "<input type='text' class='form-control' name='{{fname}}' data-ng-required='false' data-ng-model='Form.test'>" +
                    "</div>"

    }
});

html snippet looks like this:

<form name="form" novalidate="novalidate">
    <efield form="form" fname="test" label="field"></efield>
</form>

I'm using directive to wrap field html and angular's validation directives to reduce boilerplate code. Problem is even if data-ng-required='false' is set on the input field, parent div is getting 'form-group has error' class instead of just 'form-group'. What am I doing wrong here?

2

2 Answers

1
votes

You are running into problems due to the isolated scope you created in your directive. There are several ways to approach it. Here is one that will remove the isolated scope and use template:function(elem,attrs) instead

.directive('efield', function () {
    return {
        restrict: 'E',

        template: function (elem, attrs) {

            return "<div data-ng-class=\"" + attrs.form + "." + attrs.fname + ".$valid ? 'form-group' : 'form-group has-error'\">" +
                "<label class='control-label' for='" + attrs.fname + "'>" + attrs.label + "</label>" +
                "<input type='text' class='form-control' name='" + attrs.fname + "' data-ng-required='false' data-ng-model='Form.test'>" +
                "</div>"

        }
    });

Now scope will be that of the parent scope