angular指令如何绑定控制器的服务数据

时间:2016-07-19 05:11:04

标签: angularjs angularjs-directive angularjs-controller

controller:
service.checkSub(function(data){
  $scope.showSub = data.subscribe? false : true;
})

directive:
app.directive('showSub', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            showSub: '=show'
        },
        templateUrl: '<div data-ng-show="show">test</div>',
        link: function(scope, element, attrs) {
            console.log(scope.showSub); // undifined
            if(scope.showSub) {
                scope.show = true;
            }else {
                scope.show = false;
            }
        }
    }
});
<show-sub show="showSub"></show-sub>

为什么指令中的 scope.showSub 未定义,我想用它来控制指令?我该怎么办?

3 个答案:

答案 0 :(得分:0)

您的指示很好,但服务有问题。

service.checkSub(function(data){
  $scope.showSub = data.subscribe? false : true;
})

$ scope.showSub 应该在父范围内。

确保您在$ scope.showSub中有数据

答案 1 :(得分:0)

您可以按范围获取showSub的值。$ parent.showSub

所以你的代码就像..

  app.directive('showSub', function() {
   return {
    restrict: 'E',
    replace: true,
    scope: {
        showSub: '=show'
    },
    templateUrl: '<div data-ng-show="show">test</div>',
    link: function(scope, element, attrs) {
        console.log(scope.$parent.showSub); 
        if(scope.$parent.showSub) {
            scope.show = true;
        }else {
            scope.show = false;
        }
    }
  }
});

答案 2 :(得分:0)

scope.showSub给出了undefined,因为在指令中加载时,控制器作用域的showSub尚未填充。你可以做些什么来解决它:

  • templateUrl更改为template
  • ng-show="show"更改为ng-show="showSub"
  • 丢失link函数(不需要它,因为您可以直接绑定到模板中的范围变量)

代码:

app.directive('showSub', function($timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            showSub: '=show'
        },
        template: '<div data-ng-show="showSub">test</div>',
        link: function(scope, elem) {
            // this function isn't needed, but to show you it gives undefined due to the async call
            console.log(scope.showSub); // undefined
            $timeout(function(){
                console.log(scope.showSub); // true
            }, 1500);
        }
    }
});

Here is a jsfiddle