XAVI XAVI - 3 months ago 50
AngularJS Question

Unexpected compilation error when using angular js ng-attr directive

Below code I have used for adding ng-init attribute to a directive dynamically. The code is working fine and got the output as I expected but in runtime I am getting some compilation error.

angular.js:13920 Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{dashboardOptions.contentSettingsOptions.dynamicContent.enable && 'item=tileData[dashIndex].tiles[$index]' || '' }}]

<tile ng-attr-ng-init="{{dashboardOptions.contentSettingsOptions.dynamicContent.enable ?'item=tileData[dashIndex].tiles[$index]' : '' }}"
dashboard-item="tile"
ng-repeat="tile in dashitem.TileDefinitions track by $index"
>

</tile>


I am getting the expected output

<tile ng-attr-ng-init="{{dashboardOptions.contentSettingsOptions.dynamicContent.enable ?'item=tileData[dashIndex].tiles[$index]' :'' }}" dashboard-item="tile" ng-repeat="tile in dashitem.TileDefinitions track by $index" class="ng-scope angulardashboard-item tile" ng-init="item=tileData[dashIndex].tiles[$index]"></tile>


Plunker
https://plnkr.co/edit/9PBwouxYrzeKsEqtXbht?p=preview

How can I avoid this runtime error?

Answer

What are you trying to achieve by using ng-init ? ng-attr is for allowing angular to handle standard HTML attribute. A falsy value will make the attribute not showing up, a truthy value with make the attribute appear with the value.

Here you may want to do :

<div ng-init="item = canadd ? tileData[dashIndex].tiles[$index] : null">{{message}}</div>