指令未触发$ watch

时间:2018-09-21 04:44:39

标签: angularjs

我有一条指令:

function templateFn() {
        return '<div class="card-wrapper">'
            + '<div class="cards-carousel">'
            + '<div class="cards-carousel-inner">'
            + '<div ng-repeat="item in cards">'
            + '<div class="item" ng-class="{\'active\': $index == $parent.ngModel.id, \'next\' : $index == $parent.ngModel.id + 1, \'prev\' : $index == $parent.ngModel.id - 1}">'
            + '<label><input id="{{item.eid}}" type="radio" ng-value="item" ng-model="$parent.ngModel">'
            + '<img alt="{{item.id}}" ng-src="{{item.url}}" /></label>'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>';
    }

    function linkFn(scope, element, attrs) {
        scope.cards = JSON.parse(attrs.cards);
        scope.$watchCollection('cards', function(newValue, oldValue) {
            if (newValue !== oldValue) {
                scope.cards = newValue;
            }
        }, true);
    }

    return {
        restrict: 'E',
        required: ['ngModel'],
        scope: {
            ngModel: '='
        },
        link: linkFn,
        replace: 'true',
        template: templateFn
    };

在控制器中,我要求休息以取走所需的卡。像这样推卡:ctrl.cardList.push(card)

这是我的观点:

<ab-card-carousel cards="{{ctrl.cardList}}"
                  ng-model="ctrl.debitCardItem">
</ab-card-carousel>

并且在视图中,当我console.log({{ctrl.cardList}})时,它呈现的很好,并且根据需要,但未对scope。$ watch函数进行更改。 有谁能够帮助我?

1 个答案:

答案 0 :(得分:0)

从属性中删除插值:

<ab-card-carousel ̶c̶a̶r̶d̶s̶=̶"̶{̶{̶c̶t̶r̶l̶.̶c̶a̶r̶d̶L̶i̶s̶t̶}̶}̶"̶ 
                  cards="ctrl.cardList"
                  ng-model="ctrl.debitCardItem">
</ab-card-carousel>

添加单向绑定:

    scope: {
        ngModel: '=',
        cards: "<",
    },

将linkFn更改为:

function linkFn(scope, element, attrs) {
    ̶s̶c̶o̶p̶e̶.̶c̶a̶r̶d̶s̶ ̶=̶ ̶J̶S̶O̶N̶.̶p̶a̶r̶s̶e̶(̶a̶t̶t̶r̶s̶.̶c̶a̶r̶d̶s̶)̶;̶
    scope.$watchCollection('cards', function(newValue, oldValue) {
        if (newValue !== oldValue) {
            scope.cards = newValue;
        }
    }, true);
}