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

沒有留言:

FB 留言