ng-bind happend after my directive so I don't have the value

angularjs, angularjs-directive, javascript

Solution

Edit 2

The other option is to use `ng-class` or `ng-style` for changing the color of the text. Then you don't have to create a new directive at all.

Original Answer

I would not depend on the `ng-bind` directive at all... This seems much cleaner in my opinion.

<div ng-bind="someModel" my-directive="someModel"></div>

And then define your directive as...

angular.module('myApp').directive('myDirective', function() { 
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.myDirective, function(newValue, oldValue) {
              // Your Code here...
            });           
        }
    };      
});

This way you can use your directive even if you don't have an `ng-bind` on the element (for example, if you use curly braces instead).

<div my-directive="someModel">{{someModel}}</div>

Alternatively you can use `attrs.$observe(...)` (documentation) instead of `scope.$watch(...)`.

<div ng-bind="someModel" my-directive="{{someModel}}"></div>

and

angular.module('myApp').directive('myDirective', function() { 
    return {
        link: function(scope, element, attrs) {
            attrs.$observe('myDirective', function(interpolatedValue) {
              // Your Code here...
            });           
        }
    };      
});

You can find more information about the differences between `scope.$watch(...)` and `attrs.$observe()` here.

Edit

Given that your directive is basically mutating the DOM after the `ng-bind` directive, why not skip the `ng-bind` all together?

<div my-directive="{{someModel}}"></div>

and

angular.module('myApp').directive('myDirective', function() { 
    return {
        link: function(scope, element, attrs) {
            attrs.$observe('myDirective', function(interpolatedValue) {
              if (interpolatedValue) {
                // Modify interpolatedValue if necessary...
              }
              element.text(interpolatedValue == undefined ? '' : interpolatedValue);
            });           
        }
    };      
});

Problem

I have a div element with ng-bind directive: ``` <div ng-bind="sometext"></div> ``` I have a directive that gets an element, checks its value / text and adds a color to the element according to the content. I am using this directive like that: ``` <div ng-bind="sometext" my-directive></div> ``` The problem is that on the time the directive is executing, there is no value or text on the div because ng-bind didn't happened yet. I am getting the text using element.text(). Any idea how to make the text available inside my directive?

Original source

Related problems