【问题标题】:Default angularjs ng-option when data is returned from a service从服务返回数据时的默认 angularjs ng-option
【发布时间】:2013-10-16 14:02:35
【问题描述】:

到目前为止,我看到的正常解决方案都没有奏效。我的控制器从服务返回选项列表并填充选择元素没有任何问题,但我无法设置默认值。我最接近的返回错误:Cannot read property '0' of undefined,代码为$scope.new_account.account_type = $scope.new_account.account_type[0];。有了这个错误,我认为对象还没有准备好,所以我使用了一个解析来返回我的服务数据。

.when('/accounts/new/', {
    controller: function ($scope, accountTypes) {
        $scope.accountTypes = accountTypes;
        $scope.new_account.account_type = accountTypes[0];
    },
    resolve: {
        accountTypes: function (AccountService) {
            return AccountService.getAccountTypes();
        }
    }
})

但这与类似的解决方案并没有产生任何影响。选择元素被填充,但默认选项为空白。我宁愿设置一个默认选项,而不是使用带有? 值的“请选择”默认值。

我也试过

controller: function ($scope, AccountService) {
    $scope.accountTypes = AccountService.getAccountTypes();
}

通过 $scope 和 ng-init 的各种实现...

<select ng-model="new_account.account_type" ng-options="type.id as type.name for type in accountTypes" 
    ng-init="new_account.account_type='General'">

    ng-init="new_account.account_type.name='General'">

    ng-init="new_account.account_type=0">

有什么想法可以帮助为此设置默认值吗?

根据要求,accountTypes 返回[{"id":1, "name":"General"}, {"id":2, "name":"Super"}, {"id":3, "name":"Trial"}

【问题讨论】:

  • 你能发布 Fiddle/Plunker 吗?
  • 或发帖$scope.accountTypes模特
  • 这很棘手,但它应该可以工作:)
  • var data = AccountService.getAccountTypes(); $scope.mydefault = data.shift(); $scope.accountTypes = 数据;

标签: angularjs ng-options


【解决方案1】:

试试这个方法:

HTML

<div ng-controller="fessCntrl">
    <select ng-model="selectedItem" ng-options="selectedItem.name as selectedItem.name for selectedItem in values"></select>selectedItem: {{selectedItem}}
</div>

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function ($scope, Data, $timeout) {
    Data.loadData().then(function (result) {

        $timeout(function () {
            $scope.values = result;
            $scope.selectedItem = $scope.values[0].name;
        }, 2000); // dummy, to simulate delay 
    },

    function (result) {
        alert("Error: No data returned");
    });
});
fessmodule.$inject = ['$scope', 'Data', '$timeout'];


fessmodule.service('Data', ['$resource', '$q', function ($resource, $q) {
    this.values = [{
        "id": 1,
            "name": "General"
    }, {
        "id": 2,
            "name": "Super"
    }, {
        "id": 3,
            "name": "Trial"
    }];

     this.loadData = function() {
     this.deferred = $q.defer();
     this.deferred.resolve(this.values);

      return this.deferred.promise;
    };   
}]);

演示Fiddle

听起来你有问题AccountService。上面带有服务的代码是有效的

但是,如果我这样写服务:

fessmodule.service('Data', ['$resource', '$q', function ($resource, $q) {
    this.values = [{
        "id": 1,
            "name": "General"
    }, {
        "id": 2,
            "name": "Super"
    }, {
        "id": 3,
            "name": "Trial"
    }];


    this.factory = {
        loadData: function (selectedSubject) {
            this.deferred = $q.defer();
            this.deferred.resolve(this.values);

            return this.deferred.promise;
        }
    }
    return this.factory;
}]);

我收到错误:TypeError: Cannot read property '0' of undefinedFiddle

【讨论】:

  • 就像我说的:ng-init="new_account.account_type=0" 没用
  • 我看不到$scope.accountTypes请发帖或AccountService
  • 如果有帮助请告诉我
  • 不行,不行。您的方法不会引发任何错误,但初始选择选项仍为空白。感谢您的输入。我开始认为这可能是在 $routeProvider 上实现控制器的问题。我认为一个决心会解决。如果以后有时间,我会整理一个 plunkr 以更好地演示发生了什么。
  • initial select option is still blank. 什么意思?当我打开小提琴时,第一个元素被选中
【解决方案2】:

我猜你的AccountService.getAccountTypes() 会根据你的控制器代码返回一个承诺。因此,您需要等到 promise 解决后再设置默认值。没有看到 AccountService 的确切代码,我无法给出确切的答案,但我会尽我所能。

首先,忘记resolve: 位,只需在控制器中执行 GET,如下所示:

controller: function ($scope, AccountService) {
    // if your getAccountTypes accepts a success callback, do this:
    $scope.accountTypes = AccountService.getAccountTypes(function(){
        $scope.new_account.account_type = $scope.accountTypes[0];
    });
    // and if it doesn't accept a callback, do this:
    $scope.accountTypes = AccountService.getAccountTypes();
    $scope.$watch('accountTypes', function(newValue){
         if(newValue && newValue.length){
             $scope.new_account.account_type = newValue[0];
         }
    });
    // (but obviously you shouldn't need both of the above options, just one or the other)
}

希望这有意义并解决您的问题。

【讨论】:

  • 感谢您的信息,但都没有积极的结果。第一个就像 Maxim 的一样,不会更新选择。请注意,我可以 console.log 它就好了。它只是不绑定到选择。第二种方法返回未定义(使用 $watch 代替 watch)。
  • 好的。我在$watch 函数中添加了一行额外的行(感谢语法更正),试试看它是否有效...如果没有,请为您的AccountService 服务发布您的代码,我们将看看是否可以不要调试。
  • 仍然是一个空白的初始选项。虽然没有错误。我怀疑你会在我的 AccountService 中找到任何东西。只是一个 $http.get。 AccountService... return { getAccountTypes: function() { return http.get(...).then(function(result) { return results.data; }); }};
  • 您的方法没有抛出任何错误,但具有相同的非结果。没有提供默认值。服务本身只是返回一个 $http.get()。没什么特别的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 2015-09-04
  • 2011-08-07
相关资源
最近更新 更多