angular directive - 为什么不在指令中更新变量?

时间:2015-12-08 14:25:00

标签: scope directive

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

app.controller('ctrl', function($scope){
    $scope.processResultCodeList = [{key:"PRCO00",value:"All"}
                        , {key:"PRCO04",value:"Confirm"}
                        , {key:"PRCO06",value:"Return"}
                        , {key:"PRCO09",value:"Request"}];
    $scope.tempList = ["PRCO06","PRCO04"];
})
.directive('checkModel', function($compile){
    return {
        restrict: 'A',
        scope: {
            checkModel:"=",
            checkData:"="
        },
        link: function postLink(scope,elem, attrs){
           elem.on('change',function(event){
               console.log(event.target.checked);
               if(event.target.checked){
                if(scope.checkModel.some(elem=>elem!=scope.checkData)){
                    scope.checkModel.push(scope.checkData);
                }
            }else{
                scope.checkModel = scope.checkModel.filter(elem=> elem!=scope.checkData);
            }
            scope.$apply();
            $compile(elem.contents())(scope);
          });
            scope.$watch('checkModel', function(newData, oldData){
            scope.checkModel = newData;
            if(scope.checkModel.some(elem=>elem!=scope.checkData)){
                attrs.$set('checked','');
            }
            if(scope.checkModel.some(elem=>elem==scope.checkData)){
                attrs.$set('checked','checked');
            }
          },true); 

    }
};

})

我使用由键和地图组成的对象列表创建复选框。完整的复选框是绑定数组变量,在选中或取消选中时添加和删除变量的键。奇怪的值可以插入变量,但是,为什么没有删除值?

jsfiddle

p.s)抱歉,但我不擅长英语。所以如果你看错了,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试拼接数组

 if(event.target.checked){
          if(scope.checkModel.some(elem=>elem!=scope.checkData)){
                scope.checkModel.push(scope.checkData);
            }
        }else{
          scope.checkModel.splice(scope.checkModel.indexOf(scope.checkData),1)
        }

工作jsfiddle:http://jsfiddle.net/bgrpm2ap/20/