I have been struggling with a scoping issue when making an error message directive using AngularJS.
I have an ng-if and ng-class directive as part of the directive template, but the expression in the ng-class directive always seemed to return a blank string, unless:
- I removed the ng-if directive.
- or, I removed the 'replace' key in the directive definition object.
Looking at the compiled output for my directive, it looks like an isolated scope is being created if the ng-if or the replace key is removed, but if they are both left in, then there are no ng-isolate-scope classes in the html output, just ng-scope.
I would really like to understand exactly what is going on here and would be grateful for any explanations.
Directive Definition
angular.module('myMessages')
.directive('pageMessages', function() {
return {
restrict: 'E',
replace: true,
scope: {
messages: '='
},
controller: function($scope) {
$scope.severity = 'alert-success';
},
template: '<div ng-if="messages.length > 0">' +
'<div class="alert" ng-class="severity">' +
'<ul>' +
'<li ng-repeat="m in messages">{{::m.message}}</li>' +
'</ul>' +
'</div>' +
'</div>'
};
});
Output (note no alert-danger class is added)
<!-- ngIf: messages.length > 0 -->
<div ng-if="messages.length > 0" messages="messages" class="ng-scope">
<div class="alert" ng-class="severity">
<ul>
<!-- ngRepeat: m in messages -->
<li ng-repeat="m in messages" class="ng-binding ng-scope">test error</li>
<!-- end ngRepeat: m in messages --></ul>
</div>
</div>
<!-- end ngIf: messages.length > 0 --></div>
alert-danger class is added after removing replace (removing ng-if would work as well)
<page-messages messages="messages" class="ng-isolate-scope">
<!-- ngIf: messages.length > 0 -->
<div ng-if="messages.length > 0" class="ng-scope">
<div class="alert alert-danger" ng-class="severity">
<ul>
<!-- ngRepeat: m in messages -->
<li ng-repeat="m in messages" class="ng-binding ng-scope">test error</li>
<!-- end ngRepeat: m in messages -->
</ul>
</div>
</div>
<!-- end ngIf: messages.length > 0 -->
</page-messages>