While working on a project using AngularJS 1.5's new components, I encountered an issue with widget isolation. It seems that when I use the same widget multiple times, they end up sharing their controller or scope. I was under the impression that components were supposed to have completely isolated scopes. What could be causing this?
Here is a snippet of my main html template where the widgets are placed:
<widget-list
title="Books"
class="col-xs-12 col-md-4">
</widget-list>
<widget-list
title="Movies"
class="col-xs-12 col-md-4">
</widget-list>
<widget-list
title="Albums"
class="col-xs-12 col-md-4">
</widget-list>
This is the structure of my widget template:
<div class="widget widget-list">
<div class="panel b-a">
<div class="panel-heading b-b b-light">
<h5>{{$widget.title}}</h5>
<div class="pull-right">
<button type="button" class="btn btn-default btn-sm" ng-click="$widget.doSomething()">
Do something
</button>
</div>
</div>
<div class="panel-content">
{{$widget.content || 'No content'}}
</div>
</div>
</div>
This is my widget component setup:
app.component('widgetList', {
templateUrl: 'template/widget/widget-list.html',
bindings: {
title : '@',
},
controllerAs: '$widget',
controller: function($timeout) {
$widget = this;
console.log('Title on init: ', $widget.title)
$timeout(function() {
console.log('Title after 3 seconds: ', $widget.title)
}, 3000)
$widget.doSomething = function() {
$widget.content = "Something";
}
}
});
Upon running my code, the console output is as follows:
Title on init: Books
Title on init: Movies
Title on init: Albums
(3) Title after 3 seconds: Albums
Additionally, after rendering, all three widgets display No content
in their template. Oddly, when I click the doSomething()
button in any widget, only the content of the last widget updates to Something
. This behavior is confusing me. Why are my components not maintaining isolation as expected?