0

I want to call a function declared inside the link function on my directive after an ajax request on my controller. So I want to communicate the controller with the link function. This is my controller code:

.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);
         });
    }

And here is my directive code:

.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!');
           }
    };
}]);

I know that link is called after compilation, but in that moment the ajax request hasn't been finished yet. How can I do it?

Thanks.

Crisiiii
  • 409
  • 7
  • 22
  • What about setting a timeout. – sms Mar 31 '15 at 09:36
  • @sms I know when I want to call the `welcome` function inside `link`, but I don't know how I have to call it from the controller when the request is success. – Crisiiii Mar 31 '15 at 09:45

1 Answers1

3

You can't directly. You can either use events with $broadcast in your controller and $on in your directive. see this answer

or you can use $watch in your directive to look for a change in a variable your controller sets

Community
  • 1
  • 1
RoyTheBoy
  • 648
  • 1
  • 6
  • 15
  • Thanks @RoyTheBoy. Finally I've used $broadcast and $on functions to communicate controller with directive. – Crisiiii Mar 31 '15 at 10:56
  • Here there is a good example [http://jsfiddle.net/smaye81/q2hbnL5b/6/](http://jsfiddle.net/smaye81/q2hbnL5b/6/) – Crisiiii Mar 31 '15 at 11:03