Shay Friedman
Shay Friedman

Reputation: 4868

Attribute directive to work on an element inside another directive

I have hit a wall with what I need from angular, hopefully there's an easy way to achieve what I'm after.

I have a directive that looks something like that:

m.directive("string", function() {
  return {
    replace: true,
    restrict: 'E'
    scope: {'value':'='}
    template: '<div>yada yada yada <input type="text" ng-model="value"/></div>'
  };
});

I have another directive which must go on top of text input elements only:

m.directive("maskedString", function() {
  restrict: 'A',
  link: function(scope, element, attrs) {
     // ... do stuff on the element
  }
});

So... I can do that with no problem:

<input type="text" masked-string />

However, what I really need is:

<string masked-string />

This should end up setting the masked-string attribute on the input field before the template is compiled.

What is the best way to achieve that? 10x

Upvotes: 0

Views: 1167

Answers (2)

Raghu
Raghu

Reputation: 31

I suggest you use compile method of the directive for this. Here is a working fiddle - http://jsfiddle.net/R4a62/1/

myApp.directive("string", function () {
return {
    replace: true,
    restrict: 'E',
    scope: {
        'value': '='
    },
    compile:function(element, attrs){
        var newElement = angular.element('<div>yada yada yada <input type="text" masked-string ng-model="value"/></div>');
        element.replaceWith(newElement);
    }
};
});

Upvotes: 1

Patrick
Patrick

Reputation: 861

You can do this with $compile. You only need to change the top-level directive. Here's a fiddle with an example. http://jsfiddle.net/D94t7/6/

m.directive("string", function ($compile) {
    return {
        replace: true,
        restrict: 'E',
        scope: {
            'value': '=',
            'drtv': '='
        },
        link: function(scope, element, attrs) {
            var template = '<div>yada yada yada <input type="text" ng-model="value" '+ attrs.drtv +'/></div>';
            // Add the HTML
            var el = angular.element(template);
            element.append(el);
            // Compile and bind to scope
            var compiled = $compile(el);
            compiled(scope);
        }
    };
});

Upvotes: 0

Related Questions