0

HTML

<a custom-attr='{{ controller.object.value }}' data-ng-model='controller.object.value'>

Angular directive

.directive('customAttr', function () {
    return {
        require: 'ngModel',
        controller: 'ControllerName',
        controllerAs: 'cName',
        link: function (scope, el, attr, ctrl) {
            el.on('click', function ($event) {            
                if (ctrl.$viewValue && attr.customAttr) { // breakpoint
                }
            })   
        }
    }
})

Goal:

to see the correct value in attr.customAttr the first time the directive runs.

Description

Stopping at a breakpoint on the if statement inside of the directive's link function, I expect to see a boolean value. I have verified the boolean value is correct in the model using $log.log(). Unfortunately, the first time the directive runs, attr.customAttr evaluates to a string of the reference to the model value ('controller.object.value' in the debugger), and then on subsequent iterations of the directive it evaluates correctly to the boolean. I tried removing the curly braces from the attribute, and I just get an unchanging empty string.

What can I do that will cause the model value to evaluate correctly the first time?

Note: I have done a similar version of this before with a numeric value without problem. The key difference appears to be that the working version is on an input element, and has both ngModel and ngValue attributes.

Kraken
  • 5,043
  • 3
  • 25
  • 46

2 Answers2

0

Consider using

attrs.$observe('customAttr', function() {    
   scope.customAttr= scope.$eval(attrs.customAttr);
});

to properly double bind .attrs (and thus, probably resolve your issue ) to your directive.

More info in this answer and in the docs.

Community
  • 1
  • 1
illeb
  • 2,942
  • 1
  • 21
  • 35
0

As it turns out the controller and controllerAs properties were having an effect on this. I removed it, but then decided I would rather have the controller so instead I used isolate scope to evaluate the object instead of reading it from the attr property.

Kraken
  • 5,043
  • 3
  • 25
  • 46