Angular Component with controller
In the last post we discussed how to create a simple component without a controller. In this post we will add controller to the component.
Controller in component is pretty much similar to the controller in directive.
Component with controller will look something like :
var app = angular.module('app', [ ]);
var moviesController=function(){
}
app.component('movieList', {
templateUrl:'movie-list.html',
controller:moviesController
});
We need to use "ControllerAs" syntax if we want to add data or functions on the controller as shown below
var moviesController=function(){
var vm=this;
vm.movies=[
{title:'Star wars',rating:8,genre:'Action'},
{title:'Shawshank Redemption',rating:9.3,genre:'Drama'},
{title:'God Father I',rating:9.2,genre:'Crime'},
{title:'God Father II',rating:9.1,genre:'Crime'},
];
};
app.component('movieList', {
templateUrl:'movie-list.html',
controllerAs:'vm',
controller:moviesController
});
var vm=this;
vm.movies=[
{title:'Star wars',rating:8,genre:'Action'},
{title:'Shawshank Redemption',rating:9.3,genre:'Drama'},
{title:'God Father I',rating:9.2,genre:'Crime'},
{title:'God Father II',rating:9.1,genre:'Crime'},
];
};
app.component('movieList', {
templateUrl:'movie-list.html',
controllerAs:'vm',
controller:moviesController
});
And my view will look something like
<h1>Movie List</h1>
<table class="table">
<tr>
<th>Title</th>
<th>Genre</th>
<th>Rating</th>
</tr>
<tr ng-repeat="movie in vm.movies">
<td>{{movie.title}}</td>
<td>{{movie.genre}}</td>
<td>{{movie.rating}}</td>
</tr>
</table>
Working demo can be found here
Comments
Post a Comment