从控制器Angularjs调用链接功能

时间:2015-03-31 09:30:52

标签: javascript angularjs angularjs-directive

我希望在我的控制器上发出ajax请求后调用在我的指令的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请求还没有完成。我该怎么办?

感谢。

1 个答案:

答案 0 :(得分:3)

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

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