简体   繁体   中英

AngularJS custom directive $watch doesn't work

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
                });
            }
        };
...

When i click in my buton i call the search.calendar who initilaize my $scope.calendar but my watch in my directive isn't being called after.

How can I watch for the value of mtxMatrice="calendar" to be updated?

You are writing wrong syntax to watch an scope attribute. Change your code from

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM