有些時候,某些變數會直接定義在 HTML 的 ng-init 中(例如是透過 backend 吐出來的值等等)
如果要在 AngularJS Controller 中取得該變數,必須利用 $watch 來處理
HTML
1 | < div ng-controller = "TestCtrl" > |
2 | < div ng-init = "message = 'Hello'; name = 'Tom'" ></ div > |
3 | </ div > |
Javascript
1 | // 利用 $watch 確定是否 init 完成 |
2 | $scope.$watch( 'message' , function () { |
3 | console.log($scope.message); |
4 | }); |