In this article, I do not try to code myself, just understand AngularJS in a high-level view.
- Before we start, we should install Node, npm, Grunt, Bower and Yeoman.
1 2
| #This will install the latter three tools npm install -g yo grunt-cli bower
|
- Now, let’s install AngularJS generator, which is a Yeoman generator for AngularJS.
1
| npm install -g generator-angular
|
After you run grunt serve
, you will see the page as below:
Now, I am going to add the todo list from official AngularJS page to this demo.
- Create
todo.html
in app/views
folder with the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <div ng-controller="TodoCtrl"> <span>{{remaining()}} of {{todos.length}} remaining</span> [ <a href="" ng-click="archive()">archive</a> ] <ul class="unstyled"> <li ng-repeat="todo in todos"> <input type="checkbox" ng-model="todo.done"> <span class="done-{{todo.done}}">{{todo.text}}</span> </li> </ul> <form ng-submit="addTodo()"> <input type="text" ng-model="todoText" size="30" placeholder="add new todo here"> <input class="btn-primary" type="submit" value="add"> </form> </div>
|
- Create
todo.js
in app/scripts/controllers
folder with the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| 'use strict';
angular.module('angularJsDemoCodeApp') .controller('TodoCtrl', function ($scope) {
$scope.todos = [ {text:'learn angular', done:true}, {text:'build an angular app', done:false}]; $scope.addTodo = function() { $scope.todos.push({text:$scope.todoText, done:false}); $scope.todoText = ''; }; $scope.remaining = function() { var count = 0; angular.forEach($scope.todos, function(todo) { count += todo.done ? 0 : 1; }); return count; }; $scope.archive = function() { var oldTodos = $scope.todos; $scope.todos = []; angular.forEach(oldTodos, function(todo) { if (!todo.done) { $scope.todos.push(todo); } }); }; });
|
- Change
app.js
to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| 'use strict';
angular .module('angularJsDemoCodeApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl' }) .when('/about', { templateUrl: 'views/about.html', controller: 'AboutCtrl' }) .when('/todo', { templateUrl: 'views/todo.html', controller: 'TodoCtrl' }) .otherwise({ redirectTo: '/' }); });
|
Modify index.html
menu as:
1 2 3 4 5
| <ul class="nav nav-pills pull-right"> <li class="active"><a ng-href="#">Home</a></li> <li><a ng-href="#/about">About</a></li> <li><a ng-href="#/todo">Todo</a></li> </ul>
|
- Add
.done-true { text-decoration: line-through; color: grey;}
to main.css
.
Now, we are all set.