AngularJS Lesson 3 : Some Points on ng-controller
These are some points
- This directive is used to bind the scope of the view with the controller.
- If your controller is performing too much processing, you can use nested controllers .i.e. a controller within another to delegate specific behavior to another controller.
- 8) <body ng-controller="ParentCtrl">
- 9) <input ng-model="name" /> {{name}}
- 10)
- 11) <div ng-controller="ChildCtrl">
- 12) <input ng-model="name" /> {{name}} - {{$parent.name}}
- 13) </div>
- 14) </body>
- Controllers are useful in sharing objects or create common behavior for event callback functions.
- Controllers are classes which indicate Angular about the application model by connecting them to $scope object passed into your controller.
- The controller uses parameters which are dependencies, injected by AngularJS injector service. These are services that are used inside the controller.
- The DI in Angular works by matching the names of the parameters, when we declare function as function someController($scope) {}, the injector finds the $scope service from the parameter name.
- The following is an example usage of ng-controller, it has 2 files the main html file and the controller file;
- ControllerTest.html
- <html>
- <head>
- <title>Angular JS Modules</title>
- <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
- <script src = "controller1.js"></script>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
- </head>
- <body>
- <div class="jumbotron">
- <h1>ng-controller</h1>
- </div>
- <div ng-app = "appMainModule" ng-controller = "teamsController">
- <table class="table table-striped" border=1>
- <tr>
- <th>Team Name </th>
- <th>City </th>
- <th>Rank </th>
- </tr>
- <tr ng-repeat = "team in team.info">
- <td>{{ team.name }}</td>
- <td>{{ team.city }}</td>
- <td>{{ team.rank }}</td>
- </tr>
- </table>
- </div>
- </body>
- </html>
Controller.js
- var appMainModule = angular.module("appMainModule", []);
- appMainModule.controller("teamsController", function($scope) {
- $scope.team = {
- info:[
- {name:'Manchester City',city:'Manchester',rank:1},
- {name:'Arsenal',city:'London',rank:2},
- {name:'Manchester United',city:'Manchester',rank:3},
- {name:'Leicester City',city:'Leicester',rank:4},
- {name:'Liverpool',city:'Liverpool',rank:5}
- ],
- currentState: function() {
- var teamObject;
- teamObject = $scope.team;
- return teamObject.name + " " + teamObject.city+" "+teamObject.rank;
- }
- };
- });
The following is the output we get:
Comments
Post a Comment