---
layout: angular
title:  "Angularjs $scope"
date:   2016-01-01
author: Hao
category: blog
description: Angularjs $scope 笔记， 深入了解一下， 从angularjs github wiki 以及各种stackflow中搜索到的例子...
---

### JavaScript Prototypal Inheritance

首先你需要了解javascript本身的继承机制，这对你了解angularjs scope有着至关重要的作用，让我们先来复习一下。

假设`parentScope`有aString, aNumber, anArray, anObject, aFunction 5种属性， 而且`childScope`继承自`parentScope`。如果我们想从`childScope`获得`parentScope`中定义的属性，那么JavaScript会先从child scope中找，找不到，再去`parentScope`中找

下面这个例子详细说明了JavaScript Prototypal Inheritance
<iframe src="http://jsfiddle.net/hchen1202/e9257kt1/embedded/" style="width: 100%; height: 300px;"></iframe>

String & Num

      childScope.aString = 'child string'

The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name.

Array & Object & Funciton

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

The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created.

### Angular Scope Inheritance

在Angularjs中

* 以下几类会生成新的`Scope`而且`inherit prototypically`: ng-repeat, ng-include, ng-swith, ng-view, ng-controller, directive with scope: true, directive with transclude: true.
* 以下生成新的 `isolate scope`，directive with scope: {...}
* `default directive` 不会生成 `new scope`, 默认`directive` scope: false

#### ng-include
每一个ng-include都会产生一个新的`child scope`, 都会prototypically inherit from `parent scope`.

<iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/hchen1202/z5q33kg6/embedded/" ></iframe>

当在第一个input中改变值时，hide/shaddow parent scope. 我们可以改变第一个template，达到我们想要的效果。

    <input ng-model="$parent.myPrimitive">

当改变第二值时，没有产生新的`child property`, `prototypal inheritance` 发生了。

#### ng-switch
ng-swith跟ng-include一样， 如果你要`two-way binding`, use $parent, or change the model to be an object and then bind to a property of that object.

#### ng-repeat
ng-repeat有些许不一样，每个item，`ng-repeat`都会生成一个新的scope，都从`parent scope` prototypically inherit, 但同时把item的值赋给`child scope`的新属性。
<iframe style="width: 100%; height: 300px;" src="http://jsfiddle.net/hchen1202/5ye3amjd/1/embedded/" ></iframe>

#### ng-controller
ng-controller没有什么不同，但如果想要从不同的controller中share data，建议还是用`service`
