AngularJS自定义指令$ watch不起作用

时间:2014-12-29 08:34:30

标签: javascript angularjs

HTML:

<mtx-matrice-form mtxMatrice="calendar"></mtx-matrice-form>

JS:

'use strict';

angular.module('matrixarMatrice', []).directive('mtxMatriceForm', function () {
    return {
        restrict: 'E',
        templateUrl: 'views/matrice/matrice.html',
        scope: {
            mtxMatrice: '='
        },
        link: function (scope, element, attrs) {
            var updateDisplay = function () {
                //TODO
                for (var goDate in scope.outwardDates) {
                    console.log(goDate);
                }
            };
            scope.$watch(scope.mtxMatrice, updateDisplay, true);
        }
    };
});

JS:

'use strict';

angular.module('matrixarSearch', [
    'mm.foundation',
    'matrixarConfig',
    'matrixarAutocomplete',
    'matrixarCalendar',
    'matrixarMatrice'
]).controller('MainController', function ($scope, $translate, CitiesService, SearchService, mtxConstants) {
...
        search.calendar = function (id) {
            if (search.origin && search.destination && search.goDate && search.returnDate) {

                if (search.goDate) {
                    var tmpGoDate = search.goDate; // needs 2014-12-23
                    goDate = tmpGoDate.split('/').reverse().join('-');
                }
                if (search.returnDate) {
                    var tmpReturnDate = search.returnDate; // needs 2014-12-23
                    returnDate = tmpReturnDate.split('/').reverse().join('-');
                }

                SearchService.search(search.origin.rrCode, search.destination.rrCode, goDate, returnDate, search.paxes.value, search.typo.value, search.card.value).then(function (data) {
                    $scope.calendar = data;
                }).catch(function (rejection) {
                    //TODO gérer les erreurs
                });
            }
        };
...

当我点击我的按钮时,我打电话给我search.calendar初始化的$scope.calendar,但我的指示中的监视不会被调用。

如何查看要更新的mtxMatrice="calendar"的值?

1 个答案:

答案 0 :(得分:4)

您正在编写错误的语法来观察范围属性。从

更改您的代码
scope.$watch(scope.mtxMatrice, updateDisplay, true);

scope.$watch('mtxMatrice', updateDisplay, true);