DIV CSS 佈局教程網

AngularJS $scope 重點整理:ng-repeat 下的隔離 scope 與 $parse 寫回模型
編輯:關於JavaScript     

$scope 是 AngularJS 中 controller 與 view 之間的橋樑。它最容易被忽略的特性是:ng-repeat 會為每一個迭代項目建立一個子 scope,因此在自訂 directive 裡直接改 scope 屬性,可能改到的是子 scope 而非父 scope。本文用範例說明如何正確寫回。

程式碼

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>$scope 示例</title>
</head>
<script src="js/jquery.js"></script>
<script src="js/angular.min.js"></script>
<body ng-app="app" ng-controller="c">
  <div dir ng-repeat="item in items" ng-model="m">
    {{item}} + {{m}} <br>
  </div>
</body>
<script>
var app = angular.module("app", []);

function c($scope){
  $scope.items = [1, 2, 2, 3, 4, 5, 5];
  $scope.m = "string";
};

app.directive("dir", function($parse){
  return {
    compile: function($compile){
      return function(s, e, a){
        // a.ngModel 就是 ng-model 屬性的值,此處為字串 "m"

        // 寫法一:直接指定 scope 屬性
        s.m = "sdfs____#@$#@$#@$@#$__dfd";

        // 寫法二:用 $parse 動態解析後 assign,效果與上面相同
        // $parse(a.ngModel).assign(s, "新的值");
      }
    }
  }
});
</script>
</html>

為什麼需要 $parse().assign()

範例中 s.m = "..."; 與 $parse(a.ngModel).assign(s, "...") 效果一模一樣,既然如此為何要多此一舉?因為屬性名稱是動態的。

寫死 s.m 的前提是你事先知道 ng-model 寫的是 "m"。但 directive 本質上是可重複使用的元件,它的使用者可能寫 ng-model="userName"、ng-model="user.profile.email",甚至 ng-model="items[0].name"。$parse 能把這些表達式字串編譯成函式,.assign(scope, value) 則負責把值寫回表達式所指向的確切位置,包括巢狀屬性與陣列索引。

所以結論是:directive 內部若要寫入 ng-model 綁定的模型,一律用 $parse(attrs.ngModel).assign(scope, value),不要假設屬性名稱。

scope 繼承鏈與 ng-repeat 的陷阱

Angular 的 scope 是原型鏈式的:子 scope 透過原型委派讀得到父 scope 的屬性,但寫入時會在自己的層級建立同名屬性,遮蔽(shadow)掉父層的值。ng-repeat、ng-if、ng-switch 都會建立子 scope。

這導致一個經典 bug:

<div ng-repeat="item in items">
  <input ng-model="selectedName">  <!-- 每個子 scope 各有一份 -->
</div>

這裡每列輸入框改的都是各自子 scope 上的 selectedName,父層永遠是空的。解法是綁定到物件的屬性而非基本型別:

<input ng-model="form.selectedName">   <!-- 改的是父層 form 物件的屬性,共享成功 -->

因為讀取 form 時沿原型鏈找到父層的物件,修改它的屬性自然會反映到同一個物件上。這條規則被總結為 Angular 的「dot rule」:ng-model 後面永遠帶一個點。

isolate scope 的場合

若 directive 宣告了 scope: { ... }(隔離 scope),它就完全脫離原型鏈,讀不到父層任何東西,必須透過 @(字串)、=(雙向綁定表達式)、&(函式呼叫)明確聲明。這時 $parse 的作用就更明顯了——= 綁定的本質就是幫你做 $parse 與 assign。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved