2015-03-31 54 views
0

我想調用我的控制器上的ajax請求後,在我的指令中調用link函數內聲明的函數。所以我想通過鏈接功能與控制器進行通信。 這是我的控制器代碼:來自控制器的呼叫鏈接功能Angularjs

.controller('productsCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) { 

    this.courseSeriesId = $location.search().courseSeriesId; 

    //FUNCTION: get data from products to show them 
    this.getCourseSeriesProducts = function(){ 

     $http({ 
      method: 'post', 
      url: "xxx", 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
      data: { 
       functionName:'xxx', 
       courseSeriesId: this.courseSeriesId} 
     }) 
     .success(function(response) { 
      ---CODE 
      CALL welcome() function in LINK? 
      ---CODE 
     }.bind(this)) 

     .error(function(data){ 
      alert('ERROR: ' + data); 
     }); 
    } 

這裏是我的指令代碼:

.directive('nlProducts', ['$location', function($location) { 
    return { 
     restrict: 'E', 
     templateUrl: function(elem, attr){ 
      var type = ''; 
      switch($location.search().courseSeriesId){ 
       case 'en-efw': 
        type = 'tableview';break; 
      } 
      return 'xxx/nl-products-'+ type+'.php'; 
     }, 
     //control DOM elements 
     link: 
      function welcome() { 
       element.text('hi!'); 
      } 
    }; 
}]); 

我知道link被編譯後調用,但在那一刻的AJAX請求尚未結束。我該怎麼做?

謝謝。

+0

什麼。 – sms 2015-03-31 09:36:37

+0

@sms我知道我什麼時候想調用'link'裏面的'welcome'函數,但是我不知道如何在請求成功時從控制器調用它。 – Crisiiii 2015-03-31 09:45:56

回答

3

你不能直接。 您可以使用控制器中的$ broadcast事件和您的指令中的$ on。 see this answer

,或者你可以使用$手錶在你的指令,神色一變在變控制器設置有關設置超時

+0

謝謝@RoyTheBoy。最後,我使用$ broadcast和$ on函數將控制器與指令進行通信。 – Crisiiii 2015-03-31 10:56:14

+0

這裏有一個很好的例子[http://jsfiddle.net/smaye81/q2hbnL5b/6/](http://jsfiddle.net/smaye81/q2hbnL5b/6/) – Crisiiii 2015-03-31 11:03:08