首页 > 指令作用域中来自父作用域(双向绑定)的数据能否设置缺省值

指令作用域中来自父作用域(双向绑定)的数据能否设置缺省值

//parent controller
$scope.flag = {
    dragPassed: false,
    dragAllowed: false
}

//指令
return {
    scope: {
        flag: '='
    },
    link: function(scope, element, attrs) {
        //我希望flag能够有缺省值,默认情况下dragAllowed为true
        //这样方便我在其它地方调用它
        //但是下面的代码会覆盖父作用域中的dragAllowed
        if(typeof scope.flag.dragAllowed === 'undefined') {
            scope.flag.dragAllowed = true;
        }
    }
}

上面的原因是在指令链接未完成还是怎么的?试了好几种方法和变量,发现在最初的时候 console.log(typeof variable)都是undefined

在指令进行数据绑定时,什么时候才会完成绑定继而可以使用该数据进行判断呢?

请教 应该怎样设置才能够使指令作用域中的变量能够有缺省值呢?
望各位大大不吝赐教。


你是如何打出undefined,试试我的demo


angular.module('myApp', [])
        .controller('MyCtrl', function ($scope) {
            $scope.flag = {
                dragPassed: false,
                dragAllowed: false
            };
        })
        .directive('myDirective', function () {
            return {
                scope: {
                    flag: '=?'
                },
                template: '<div ng-show="flag.dragAllowed">My Directive</div>',
                controller: function ($scope) {
                    if (!$scope.flag) {
                        $scope.flag = {
                            dragPassed: true,
                            dragAllowed: true
                        };
                    }
                }
            }
        });

如果默认都是dragAllowed的话,我觉得这样改成dragNotAllowed设计会更好点

.controller('MyCtrl', function ($scope) {
    $scope.flag = {
        dragPassed: false,
        dragNotAllowed: true
    };
})

【热门文章】
【热门文章】