2017-03-22 35 views
0

我有一个角度控制器内部的函数,它调用工厂从API请求数据并调用指令内的函数,这工作正常。但是需要将检索到的数据传递给指令中的函数,并且除了'undefined'之外,我似乎无法获得指令函数内部的任何数据,而在控制器函数中它工作正常。我已经使用.then()链接数据检索和指令函数调用,使它们连续运行,但它没有帮助,我似乎无法将控制器中的函数内定义的任何东西传递给指令函数。将数据从控制器内部的函数传递到角度内的指令中的函数

我的代码如下所示:

控制器

angular.module('myControllerModule', ['getData']) 
.controller('myViewController', function($scope, getDataFactory){ 

    // Mapping the directive function to controller 
    $scope.setDirectiveFn = function(directiveFn){ 
     $scope.directiveFn = directiveFn; 
    }; 

    // the function used for the factory and directive function call 
    $scope.search = function(){ 
     $scope.RetreivedData = getDataFactory.getTheData() 
      .then(function successCallback(response){ 
       $scope.data = response.data; // This is not passed 
      }).then($scope.directiveFn()) 
    }; 
}); 

angular.module('getData',[]) 
.factory('getDataFactory', function($http){ 
    return{ 
     getTheData: function() { 
      return $http({ 
       url: 'url/to/API/endpoint', 
       method: 'GET' 
      }) 
     }, 
    } 
}); 

指令

angular.module('myChartModule') 
.directive('chart', function(){ 
    return{ 
     restrict: 'E', 
     scope: { 
      data: '=', 
      setFn: '&', 
     }, 
     controller: 'myViewControllerr', 
     templateurl: '/path/to/my/template/file.html', 
     link: function link(scope, element, attr){ 

      scope.drawChart = function(){  
      var chartData = scope.data; //undefined 
      console.log(chartData); 
      }; 
      // mapping the directive funtion to contorller 
      scope.setFn({theDirFn: scope.drawPSA}); 
     } 
    } 
}); 

HTML

<chart data= 'data' set-fn="setDirectiveFn(theDirFn)"></chart> 

我似乎无法找到一个方法来解决这个问题,而且更重要的是,我真的不知道问题出在哪里?

+0

其看来你的指令创建隔离范围,如果你想用ctrl范围,然后用ctrl是列在链接功能 –

+0

参数如果你聪明,你可以在指令设置一个观察者来设置'data'填充或不是 – Satpal

+0

@JayantPatil不确定你的意思?在控制器和指令之间已经有了与$ scope.data相关的双向绑定,并且指令函数被映射到了控制器内的一个函数。如果我在控制器的'$ scope.search'函数之外定义数据,我可以将它传递给指令中的'drawChart'函数。但是,如果我在搜索功能中定义(或更改了“数据”的值),它不会通过。 –

回答

0

终于解决了这一点。这是一个承诺链的问题。我将控制器search函数中的指令函数调用封装为匿名函数。现在数据正在通过。

$scope.search = function(){ 
    $scope.RetreivedData = getDataFactory.getTheData() 
     .then(function successCallback(response){ 
      $scope.data = response.data; 
     }) 
     .then(function(data){ 
      $scope.directiveFn($scope.data) 
     }) 
}; 
相关问题