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

how angular directive bind controller's service data

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.showSubundefined ,我想用它来控制指令?我该怎么做?

您的指令没问题,但服务有问题。

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

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

确保您在 $scope.showSub

中有数据

您可以通过范围获取 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;
        }
    }
  }
});

scope.showSub 未定义,因为在指令中加载时,控制器范围的 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