I'm trying to figure out why I'm having trouble overwriting a value passed to an angularJS directive via an isolate scope (@). I try to overwrite the value of vm.index with the following:
vm.index = parseInt(vm.index, 10)
However, it doesn't work for some reason.
If I change it to:
vm.newIndex = parseInt(vm.index, 10)
It works. Also, assigning the value on the $scope works.
Why doesn't the first method work?
I've created this example plunker for reference.
As you used
@here which need value from an attribute with{{}}interpolation directive. And seems like directive is getting loaded first & then thevm.indexvalue is getting evaluated. So the changes are not occurring in current digest cycle. If you want those to be reflected you need to run digest cycle in safer way using $timeout.Above thing is ensuring that value is converted to decimal value. The addition will occur on the on the directive html
<h2>Item {{ vm.index + 1 }}</h2>Working Demo
The possible reason behind this
As per @dsfq & my discussion we went through the angular
$compileAPI, & found that their is one method callinitializeDirectiveBindingswhich gets call only when we usecontrollerAsin directive with an isolated scope. In this function there are switch cases for the various binding@,=and&, so as you are using@which means one way binding following switch case code gets called.Code
In above code you can clear see that there they placed
attrs.$observewhich is one sort of watcher which is generally used when value is with interpolation like in our case it is the same{{index}}, this means that this$observegets evaluated when digest cycle run, That's why you need to put$timeoutwhile makingindexvalue asdecimal.The reason @dsfq answer works because he use
=provides two way binding which code is not putting watcher directly fetching value from the isolated scope, here is the code. So without digest cycle that value is getting updated.