javascript - How to properly use the same AngularJS 1.5 component multiple times in a view? -
i'm creating set of widgets angularjs 1.5's new components. problem is, when using same widget multiple times, somehow share controller or scope. thought 1 of things components scope isolated?
my main html template hold widgets:
<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>
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()"> </button> </div> </div> <div class="panel-content"> {{$widget.content || 'no content'}} </div> </div> </div>
my widget component:
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"; } } });
when running code, console looks like:
title on init: books title on init: movies title on init: albums (3) title after 3 seconds: albums
also after rendering, 3 widgets display no content
in template. but, when clicking dosomething()
button in either 1 of 3 widgets, content of last widget updates something
.
what happening here? why components not 'isolated'?
looks have global variable called $widget here, try this:
var $widget = this;
instead of
$widget = this;
it creates mess since $widget variable holds reference controller has been initialized, in case controller of third component.
Comments
Post a Comment