从控制器访问提取的资源?

时间:2014-08-13 16:35:43

标签: javascript ajax angularjs angularjs-scope

在我的AngularJS控制器中,我尝试做一些相对简单的事情:我试图在控制器中动态填充<select>元素。为此,我需要等待加载我的本地化UI文本数据,并加载来自我的服务器的数据,这对我来说是个问题。

我的HTML看起来像:

<select 
data-ng-model="group"
data-ng-options="options.value as options.label for options in userGroups">
<option>--</option>
</select>

然后我的控制器实际上正在实现一个基本控制器&#34; class&#34;这允许我在控制器之间共享逻辑:

// exampleController.js
myModule.controller('exampleController',
    ['$scope', '$timeout', '$routeParams', '$controller',
        function ($scope, $timeout, $routeParams, $controller) {
            // Instantiate the base controller class and set it's scope 
            // to this controller's scope. This is how the base and child
            // controllers will share data and communicate.
            var base = $controller('baseController', { $scope: $scope });
}]);

这是baseController的相关片段:

// baseController.js
$scope.getDataFromUrl = function (url, cache, successFunction) {
    $http.get(url, { cache: cache })
    .success(function (data) {
        if (!handleErrorInData(data))
        {
            successFunction(data);
        }
    });
};

$scope.getDataFromUrl(uiTextResourceUrl, true, function (data) {
    $scope.uiText = data;
});

因此baseController在加载时提取文本资源,并在完成检索数据后将其设置为范围。另一方面,exampleController将通过getDataFromUrl()中定义的baseController函数从服务器获取其他数据,如下所示:

$scope.getDataFromUrl(dataUrl, false, function (data) {
    // Do stuff with the returned data...
};

我的问题来自exampleController代码的这一部分,其中我填充了之前<select>元素的数据:

// exampleController.js (Continued...)

$scope.getDataFromUrl(userGroupsUrl, false, function (data) {
    initSelectDropdown(data);
});

var initSelectDropdown = function (data) {
    var userGroups = [];

    // Parse data retrieved from the server and populate the <select> bound data
    // array with it
    var index;
    for (index = 0; index < data.length; ++index)
    {
        var newGroup = {
            value: data[index],
            label: data[index]
        };

        // One of the data entries will have a value of "", this group needs its
        // label to be set to the localized string "No Group"
        if (newGroup.value === "")
        {
            newGroup.label = '<' + $scope.uiText['NoGroup.Text'] + '>';
        }
        userGroups.push(newGroup);
    }

    // Set local userGroups to scope
    $scope.userGroups = userGroups;
};

我遇到的问题是initSelectDropdown()功能。我需要同时拥有来自服务器的数据和来自服务器的uiText资源数据,特别是要以依赖于加载的本地化资源的方式转换数据的行newGroup.label = '<' + $scope.uiText['NoGroup.Text'] + '>';。我研究了这个问题并看到使用$q.all()可能是一个解决方案但不幸的是在我的情况下我无法调用$q.all(),因为两次调用获取数据是由不同的函数在不同的控制器(从子控制器请求的数据和从基本控制器请求的资源)。

在视图中,很容易解决这个问题,因为如果我将一个元素绑定到$scope.uiText['SomeText.Text'],那么它一直不关心SomeText.Text是否最初是未定义的,也不是最终的填充UI将自动获取更改。

我该如何使这项工作?是否有可能在视图中实现绑定的工作方式?

1 个答案:

答案 0 :(得分:3)

对于共享代码angular提供服务/工厂,您不需要使用基本控制器。

定义工厂类并添加两个方法,一个用于获取服务器数据,另一个用于获取uiText数据。这些方法将返回承诺。

现在在您的控制器中,您可以使用$ q.all()传递将在ajax调用完成时解析的两个promise。 希望它有意义吗?

相关问题