[JS] AngularJS Note [關於 Watcher 及 scope ]

用 TypeScript 做了一下簡單的測試,與 Knockout 的想法,有異曲同工之妙,bind-with 改由 controller 來做取代。不過光綁定這個動作… 實在加成分數太多。

<div ng-app>
 <div ng-controller="My.Helpers.C0001">
  <p>{{TestValue0 || "請輸入"}}</p>
  <input type="text" ng-model="TestValue0" />
  <input type="button" value="Remove" ng-click="Remove()"/>
  <input type="button" value="Add" ng-click="Add()"/>
 </div>

 <div ng-controller="My.Helpers.C0002">
  <p>{{TestValue1 || "請輸入"}}</p>
 </div>

 <div ng-controller="My.Helpers.C0003">
  <p>{{TestValue2 || "請輸入"}}</p>
 </div>

</div>
function toLog( obj : any) {
 console.log(obj);
}

module My.Helpers {
 export interface I0001 {
  TestValue0: string;
  Add: () => void;
  Remove: () => void;
 }
 export interface I0002 {
  TestValue1: string;
 }
 export interface I0003 {
  TestValue2: string;
 }
 export class C0001 {
  constructor($scope: I0001) {
   // 測試 $$watch 陣列當中值的變動
   $scope.TestValue0 = "C0001";
   $scope.Add = function () {
    this.TestValue0 = "C0001X";
   }
   $scope.Remove = function () {
    delete (this.TestValue0);
   }
   toLog($scope);
  }
 }

 export class C0002 {
  constructor($scope: I0002) {
   $scope.TestValue1 = "C0002";
   toLog($scope);
  }
 }

 export class C0003 {
  constructor($scope: I0003) {
   $scope.TestValue2 = "C0003";
   //每個 Ctrl 有個自的 $$watchers...
   //而 scope 也會自動分配,可以從 物件有 add 函式,
   //而物件2,3都沒有該項函式中知道
   toLog($scope);
  }
 }
}

沒有留言: