2017-03-22 42 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) 
     }) 
}; 
相關問題