AngularJs。在$ scope中循环。$ watch

时间:2014-09-12 08:45:52

标签: angularjs angularjs-scope

我无法理解什么是错的。我需要创建小时和分钟数组并向他展示。

HTML:

<div ng-app="test">
    <div ng-controller="timeCtrl" ng-init="opentime='9';closetime='24'">
        <div ng-repeat="time in times">
            <a href="#">{{time}}</a>
        </div>
    </div>
</div>

JS:

var app = angular.module('test', []);

app.controller('timeCtrl', ['$scope', function ($scope) {

    $scope.$watch('opentime', function () {

        $scope.times = [];    

        for (var hours = $scope.opentime; hours < $scope.closetime; hours++) {

        console.log(hours);

            for (var minutes = 0; minutes < 4; minutes++) {

                var linkMinutes = minutes * 15;

                if (linkMinutes === 0) {
                    linkMinutes = "00";
                }

            console.log(linkMinutes);

            $scope.times.push(hours + ':' + linkMinutes);

            }
        }


    });


}])

为什么console.log为空,但vars opentime和closetime值?

小提琴:http://jsfiddle.net/Zoomer/mj8zv2qL/

2 个答案:

答案 0 :(得分:0)

因为您的范围变量opentime从未更改为消防观察员

我更新了example并模拟了变量

答案 1 :(得分:0)

范围。$ watch仅在opentime更改值时执行,请在此处查看更多https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope

和那个演示http://jsfiddle.net/oprhy6te/ enter link description here

<强> CTRL:

app.controller('timeCtrl', ['$scope', function ($scope) {

    $scope.$watch('opentime', function () {

        $scope.updateTimes();

    });


    $scope.updateTimes = function () {
        $scope.times = [];

        for (var hours = $scope.opentime; hours < $scope.closetime; hours++) {

            console.log(hours);

            for (var minutes = 0; minutes < 4; minutes++) {

                var linkMinutes = minutes * 15;

                if (linkMinutes === 0) {
                    linkMinutes = "00";
                }

                console.log(linkMinutes);

                $scope.times.push(hours + ':' + linkMinutes);

            }
        }
    }

    function activate() {
        $scope.opentime = 9;
        $scope.closetime = 13;
        $scope.updateTimes();

    }

      activate();

}])

<强> HTML:

<div ng-app="test">
    <div ng-controller="timeCtrl">
        <input type="text" ng-model="opentime" />
        <div ng-repeat="time in times"> <a href="#">{{time}}</a> 
        </div>
    </div>
</div>