[AngularJS]Module and Controller

2018-09-25  本文已影响0人  SharlotteZZZ

An AngularJS module defines an application. It is also a container for the application controllers.

Advantages:
Global functions should be avoided in JavaScript. They can easily be overwritten or destroyed by other scripts.
AngularJS modules reduces this problem, by keeping all functions local to the module.

Simple example:
1.Creating a Module using angular.module
2.Add a controller to your application, and refer to the controller with the ng-controller directive.

In myApp.js file:

var app = angular.module("myApp", []); 

The [] parameter is a list of dependent modules.
Without the [] parameter, you are retrieving an existing one.

In myCtrl.js file:

app.controller("myCtrl", function($scope) {
     $scope.firstName = "John";
     $scope.lastName= "Doe";
 }); 

$scope

If we consider an AngularJS application to consist of:

The scope is a JavaScript object with properties and methods, which are available for both the view and the controller.

(1)When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties.

<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.carname = "Volvo";
});
</script>

<p>The property "carname" was made in the controller, and can be referred to in the view by using the {{ }} brackets.</p>

</body>

(2)If you make changes in the view, the model and the controller will be updated:

When you type the name in the input field, the changes will display real time in label h1, because it affect the model, and the name property in the controller

<body>

<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1>My name is {{name}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name = "John Doe";
});
</script>

</body>

Root Scope

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.

The rootScope is available in the entire application.

If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

Controller's color variable does not overwrite the rootScope's color value.

<body ng-app="myApp">

<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>//blue

<div ng-controller="myCtrl">

<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1> //red

</div>

<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1> //blue

<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
    $rootScope.color = 'blue';
});
app.controller('myCtrl', function($scope) {
    $scope.color = "red";
});
</script>

</body>
上一篇 下一篇

猜你喜欢

热点阅读