从控制器 Angularjs 调用 link 函数

Call link function from controller Angularjs

我想在我的控制器上发出 ajax 请求后,在我的指令中调用在 link 函数内声明的函数。所以我想用 link 函数与控制器通信。 这是我的控制器代码:

.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请求还没有完成。我该怎么做?

谢谢。

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

或者您可以在指令中使用 $watch 来查找控制器设置的变量的变化