顯示具有 AngularJS 標籤的文章。 顯示所有文章
顯示具有 AngularJS 標籤的文章。 顯示所有文章

2013-09-05

$scope.$watch() 監視 model

$scope.$watch() 可以用來監視 model 值。
<html ng-app>
<meta charset="utf-8">
<body ng-controller='myController'>
    <input ng-model="my.input" placeholder="填入整數" />
    <p>填入值: {{my.input}}</p>
    <p ng-bind="my.dots"></p>

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script>
    function myController($scope) {
        $scope.my = {
            input: 0,
            dots: ''
        };
        $scope.$watch('my.input', function(newValue, oldValue, scope) {
            // console.log(':::', newValue, oldValue, scope);
            alert('new value:' + newValue);
            var dot = '◎';
            var i = parseInt($scope.my.input);
            $scope.my.dots = '';
            while (i-- > 0) {
                $scope.my.dots += dot;
            }
        });
    }
    </script>
</body>
</html>
範例 ng_scope_watch.htm

AngularJS 非全域 controller 設定方式

<html ng-app='myApp'><!-- 設定模組名稱為 myApp -->
<meta charset="utf-8">
<body ng-controller='myController'>
    <p>Hello {{txt}}</p>
    <p ng-bind=" 'Hi ' + txt"></p><!-- 未完成動作前無顯示內容 -->

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script>
    // 建立名稱為 myApp 的模組。第二個參數空陣列表示 "建立", 沒有給表示 "取得"
    var myAppModule = angular.module('myApp', []);
    
    // 設定 controller
    myAppModule.controller('myController',
        function($scope) {
            $scope.txt = "John";
        });
    </script>
</body>
</html>
AngularJS 非全域 controller 設定方式:

  • 以 ng-app 設定模組名稱。
  • angular.module() 建立模組。
  • 以模組的 controller() 設定控制器。


ng-bind 和 {{}} 都是設定 data-binding 的方式。ng-bind 的優點是 AngularJS 尚未處理完時,不會出現模版文字。

AngularJS 概念

AngularJS 是目前相當熱門的 JS framework, 好像不學一下就快跟不上技術了。

最近看到的資源:
範例: http://tutorialzine.com/2013/08/learn-angularjs-5-examples/
影片教學: http://egghead.io/lessons

AngularJS 主要概念(參考  Oreilly AngularJS):

  • Client-Side Templates
  • MVC
  • Data Binding
  • Dependency Injection
  • Directives

練習、修改了書中的 Shopping Cart 例子,ng_cart01.htm。
個人修改時的要點:
  • ng-init 初始化。
  • ng-repeat="item in items" 裡 $index 是預設的索引變數。
  • ng-keyup 事件在 1.1.5 之後的版本才有效。

FB 留言