AngularJs學習筆記--Understanding the Model Component


原版地址:http://docs.angularjs.org/guide/dev_guide.mvc.understanding_model

 

  在angular文檔討論的上下文中,術語“model”可以適用於單一對象代表一個實體(例如,一個叫” phones”的model,它的值是一個電話數組。)或者作為應用的全部數據Model(所有實體)。

  在angular中,model可以是任意數據,可以通過angular的scope對象的屬性來獲取model。屬性的名稱是model的標識,值可以是任意javascript對象(包括數組和原始數據)。

  javascript想成為model的唯一的條件是對象必須作為一個scope對象的屬性被angular scope引用。屬性的引用關系可以明確或者隱含地創建。

  我們可以通過以下幾種方式來顯式創建scope的屬性,關聯javascript對象來創建model:

  • 在javascript代碼中,直接賦值給scope對象的屬性;這通常發出現在controller中:
function MyCtrl($scope) {

     // create property 'foo' on the MyCtrl's scope

     // and assign it an initial value 'bar'

     $scope.foo = 'bar';

 }
  • 在模版的angular表達式(http://www.cnblogs.com/lcllao/archive/2012/09/16/2687162.html)中,使用賦值操作符:
<button ng-click="{{foos='ball'}}">Click me</button>
  • 在模版中使用ngInit directive(http://docs.angularjs.org/api/ng.directive:ngInit)(僅僅作為例子,不推薦在真實應用中使用)
<body ng-init=" foo = 'bar' ">

 

  angular在下面的模版結構中會隱式創建model:

  • 表單的input 、select、textarea和其他form元素:
<input ng-model="query" value="fluffy cloud">

  上面的代碼,在當前的scope中創建了一個叫”query”的model,並且與input的value值綁定,初始化為”fluffy cloud”。

  • 在ngRepeater中聲明迭代器
<p ng-repeat="phone in phones"></p>

  上面的代碼為每一個phones數組的元素各自創建了一個child scope,並且在對應的child scope中創建”phone”model,賦予數組中對應的值。

  在angular中,當出現下面的情況時,javascript對象將不再是一個model:

  • 當沒有angular scope包含與該對象關聯的屬性時。
  • 所有包含與對象關聯的屬性的angular scope成為了陳舊和適合垃圾回收時。

  下面的插圖展示了在一個簡單的模版中隱式創建一個簡單的數據model。

 

By Lcllao.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM