2015-03-31 142 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