简体   繁体   中英

Call link function from controller Angularjs

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM