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.

2
  • What about setting a timeout. Commented Mar 31, 2015 at 9: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. Commented Mar 31, 2015 at 9:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @RoyTheBoy. Finally I've used $broadcast and $on functions to communicate controller with directive.
Here there is a good example http://jsfiddle.net/smaye81/q2hbnL5b/6/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.