控制器功能作为回调执行

时间:2014-10-22 06:22:24

标签: javascript angularjs

我将html的部分(div)更改为指令,在更改之前,我的html看起来像这样:

<div ng-controller="SearchCtrl as search">
    <div id="firstDirective">
        .
        .
        .
    <div>
    <div id="secondDirective">
        .
        .
        .
    <div>
</div>

与关联的控制器一起工作正常。我计划将html更改为:

<div ng-controller="SearchCtrl as search">
    <first-directive>
    <second-directive>
</div>

相应的angular.directive定义具有隔离范围(return {..., scope: {attr: '=attr', func: '&func'},...}),并且从控制器传递属性和函数。 将第一个div更改为指令(first-directive)后,它仍然运行良好。但是,在创建second-directive并替换相应的div之后,该部分不再起作用(第一个仍然有效)。这是我的控制器:

app.controller('SearchCtrl', ['$scope', '$http', function($scope, $http){

    var self = this;

    self.data = {};

    self.clickSearch = function() {

        self.retrieve(param1, param2);
        .
        .
        .
        console.log('clickSearch log, data: ', self.data);
    }

    // retrieve is reused, called directly in some parts of html, 
    // thus I attached it as a controller function
    self.retrieve = function(param1, param2) {

        // some $http.get and assign to data
        .
        .
        .

        console.log('retrieve log, data:', self.data);
    }
    // some other functions, some are passed to the directives
    .
    .
    .
});

然而日志显示:

[LOG]clickSearch log, data: {}
[LOG]retrieve log, data: {...//some assigned values}

看起来clickSearch函数首先完成,然后retrieve函数执行,因此我得到空数据。我的背景来自Java,所以我不完全理解JavaScript中回调的概念,我怀疑这就是发生了什么。我怎么能补救这个?感谢。

1 个答案:

答案 0 :(得分:1)

试试这个

app.controller('SearchCtrl', ['$scope', '$http', function($scope, $http){

var self = this;

self.data = {};

self.clickSearch = function() {

    self.retrieve(param1, param2, function(data){
       .
       .
       .
        console.log('clickSearch log, data: ', data);
        console.log('clickSearch log, data: ', self.data);
    });
}

// retrieve is reused, called directly in some parts of html, 
// thus I attached it as a controller function
self.retrieve = function(param1, param2, callback) {

    // some $http.get and assign to data
    .
    .
    .

    console.log('retrieve log, data:', self.data);
    callback(data);//$http.get{url:url,success:callback}
}
// some other functions, some are passed to the directives
.
.
.

});