【问题标题】:Loop through angular js array in javascript循环通过javascript中的角度js数组
【发布时间】:2014-11-25 22:44:05
【问题描述】:

我有一个将List<KeyValuePair<string, byte>> 返回到 Angular js 工厂的 web api。然后我使用 ->

在选择中呈现它
<select ng-model="survey.surveyType" class="form-control" id="surveyType">
                    <option ng-repeat="surveyType in surveyTypes" value="{{surveyType.value}}">{{surveyType.key}}</option>
                </select>

这很好用。 Angular 循环并正确显示对象。当与 web api 方法交谈时,我已经像这样配置它 ->

app.factory('Survey', ['$resource', function ($resource) {
return $resource('http://localhost:52133/api/surveyapi/:id', null,
    {
        'update': { method: 'PUT' },
        'getSurveyTypesAsDictionary': { method: 'GET', isArray: true, url: 'http://localhost:52133/api/surveyapi/GetSurveyTypesAsDictionary' }
    });
}]);

// fetching the values in my controller
var surveyTypes = Survey.getSurveyTypesAsDictionary();

现在我的问题是这个。我无法循环结果。在控制台中,对象看起来像这样 ->

但是,如果我尝试获取角度数组中的值,则那里什么也没有。例如surveyTypes.length 为 0。

问题。如何使用 JavaScript 使用数组? 谢谢!

编辑: 我试图从 web api 只返回 Dictionary&lt;string, byte&gt;,但我根本没有让它工作。

编辑,对 Sergiu 发表​​评论:

var promise = Survey.getSurveyTypesAsDictionary();
promise.$promise.then(function (response) {
    console.log(response.length);
});

为了使您的建议发挥作用,我必须从对象中获取$promise。这是正确的还是我需要配置我的工厂以使其按照您的语法编写方式工作?

【问题讨论】:

标签: javascript angularjs asp.net-web-api angularjs-factory


【解决方案1】:

首先,返回的resource object 具有提供高级行为的操作方法,而无需与低级$http 服务交互。

例如

Post.query(function(data) {
    $scope.posts = data;
});

或者,您也可以通过返回对象的$promise 属性访问原始的$http 承诺

 var req = Post.query().$promise;
 req.then(function(data) { 
     $scope.posts = data;
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 2013-12-23
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    相关资源
    最近更新 更多