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.