Angularjs指令双向绑定不会更新html

时间:2016-05-22 11:07:35

标签: angularjs angularjs-directive angularjs-scope

我创建了一个日历指令。我的意图是当我按下“更改”按钮更新日历日期。虽然当我检查范围时,calendarDate会更新,但在标记中它仍然是相同的。知道我做错了什么吗? 这是代码:

var DailyTimekeeping = TimekeepingsApp.controller('DailyTimekeeping', [
    '$scope', 'UserService', '$http', function($scope, UserService, $http) {
        var self = this;
        self.currentDate = new Date();
        $scope.init = function(userId) {
            self.currentDate = new Date();
        }

    } ]);

 var calendar = TimekeepingsApp.directive('calendar', ['$timeout',    function($timeout) {
return {
    restrict : 'E',
    scope : {
        calendarDate : '=date'
    },
    templateUrl : 'angular/calendar.html',
    link: function (scope, element, attrs) {
        scope.$watch('calendarDate', function() {
            element.on('click', '.change' ,function (e) {
                   alert('Test');
                   scope.calendarDate.setDate(10);
                });
         });

    }
};

和calendar.html

<div class="container-fluid calendar-component">
<div class="row">
    <div class="col-md-12 text-center calendar-month">
        <span> {{calendarDate}} </span>
    </div>
</div>
<div class="row calendar-day">
    <div class="col-md-12 text-center"> <a class="change"">Change </a></div>
    <div class="col-md-12 text-center day-number">{{calendarDate | date: 'dd'}}</div>
    <div class="col-md-12 text-center day-name">{{calendarDate | date: 'EEEE'}}</div>
</div>

使用此组件:

calendar date="dailyTimekeeping.currentDate">

1 个答案:

答案 0 :(得分:0)

您的问题是element.on仅仅是在事件发生时连接回调。由于您的回调发生在Angular行为的正常方案之外,因此无法知道您的范围变量已更改(通过名为digest cycle的内容)。

您可以通过将更新代码放在scope.$apply(...)调用中来解决此问题,因为这会告诉Angular在代码执行后运行摘要:

...
element.on('click', '.change' ,function (e) {
    alert('Test');
    scope.$apply(function() {
        scope.calendarDate.setDate(10);
    });
});
...
相关问题