Exploring the super tutorial of Scope object in AngularJS framework

Source: Internet
Author: User
This article mainly introduces how to use Scope objects in AngularJS framework, including differences between Scope and rootscope. For more information, see I. Problems Encountered
The problem occurs when AngularJS is used to nest the Controller. Because each Controller has its corresponding Scope (equivalent to Scope and control Scope), the nested Controller means the nesting of Scope. In this case, what will happen if both scopes have a Model with the same name? How to update the Model in the parent Scope from the sub-Scope?

This problem is typical. For example, if the current page is a product list, you need to define a ProductListController

function ProductListController($scope, $http) {  $http.get('/api/products.json')    .success(function(data){      $scope.productList = data;    });  $scope.selectedProduct = {};}

You probably see that a selectedProduct Model is also defined in Scope, indicating that a product is selected. At this time, the product details will be obtained, and the page will be automatically updated through $ routeProvider in AngularJS to pull a new details page template, which contains a ProductDetailController

function ProductDetailController($scope, $http, $routeParams) {  $http.get('/api/products/'+$routeParams.productId+'.json')    .success(function(data){      $scope.selectedProduct = data;    });}

An interesting thing happened. Here there is also a selectedProduct. How does it affect selectedProduct in ProductListController?

The answer is no effect. In AnuglarJS, the sub-Scope will indeed inherit the objects in the parent Scope, but when you try to bind two-way data of the basic data type (string, number, boolean, some strange behaviors will be discovered, and inheritance does not work as you think. The attributes of the sub-Scope hide (overwrite) the attributes of the same name in the parent Scope. Changes to the sub-Scope attributes (form elements) do not update the values of the parent Scope attributes. This behavior is not actually unique to AngularJS, and the prototype chain of JavaScript itself works like this. Developers generally do not realize that ng-repeat, ng-switch, ng-view, and ng-include all create their new subscopes, so they often encounter problems when using these direve ve.

Ii. Solution
The solution is not to use the basic data type, but to add more points to the Model.

Use

 

To replace

 

Isn't it so boring? The following example clearly shows what I want to express.

app.controller('ParentController',function($scope){  $scope.parentPrimitive = "some primitive"  $scope.parentObj = {};  $scope.parentObj.parentProperty = "some value";});app.controller('ChildController',function($scope){  $scope.parentPrimitive = "this will NOT modify the parent"  $scope.parentObj.parentProperty = "this WILL modify the parent";});

View Online DEMO
But I really need to use the original data types such as string number. What should I do? Two methods --

Use $ parent. parentPrimitive in the subscope. This will prevent the sub-Scope from creating its own attributes.
Define a function in the parent Scope so that the sub-Scope can call and PASS Parameters of the original data type to the parent to update attributes in the parent Scope. (Not always feasible)
Iii. JavaScript prototype chain inheritance
Let's take a closer look at the prototype chain of JavaScript. This is very important, especially when you switch from server-side development to the front-end, you should be familiar with the classic Class inheritance. Let's review it.

Assume that the parent parentScope class has the following attributes: aString, aNumber, anArray, anObject, and aFunction. The child-class childsscope prototype inherits the parentScope of the parent class, so we have:

If the sub-Scope tries to access the attributes defined in parentScope, JavaScript will first search in the sub-Scope. If this attribute is not available, it will find the inherited scope to obtain the attributes, if this attribute is not found in the inherited prototype object parentScope, continue searching in its prototype until it reaches rootScope. Therefore, the following expression returns true:

childScope.aString === 'parent string'childScope.anArray[1] === 20childScope.anObject.property1 === 'parent prop1'childScope.aFunction() === 'parent output'

Suppose we execute the following statement

childScope.aString = 'child string'

The prototype chain is not queried. Instead, a new aString attribute is added to childs.pdf. This new property hides (overwrites) attributes of the same name in parentScope. The concept of ng-repeat and ng-include is very important.

Suppose we perform this operation:

childScope.anArray[1] = '22'childScope.anObject.property1 = 'child prop1'

The prototype chain is queried because the anArray and anObject objects are not found in childs.pdf. They are found in parentScope and their values are updated. No new attributes are added to childs.pdf, and no new objects are created. (Note: In JavaScript, array and function are both objects)

Suppose we perform this operation:

childScope.anArray = [100, 555]childScope.anObject = { name: 'Mark', country: 'USA' }

The prototype chain is not queried, and the sub-Scope adds two new object attributes, which hide (overwrite) the attributes of the same name object in parentScope.

Summary

If childScope. propertyX is read and childScope has properties propertyX, the prototype chain is not queried.
If childScope. propertyX is set, the prototype chain is not queried.
In the last case,

delete childScope.anArraychildScope.anArray[1] === 22 // true

We deleted the attribute from childScope. When we access this attribute again, the prototype chain will be queried. Deleting an object property will expose the property from the prototype chain.

Iv. Scope inheritance of AngularJS
Create a new Scope and the prototype inherits: ng-repeat, ng-include, ng-switch, ng-view, ng-controller, directive with scope: true, directive with transclude: true
Create a new Scope, but do not inherit: directive with scope :{...}. It creates an independent Scope.
Note: by default, directive does not create a new Scope, that is, the default parameter is scope: false.

ng-include

Assume that in our controller,

$scope.myPrimitive = 50;$scope.myObject  = {aNumber: 11};

HTML:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.