Angular js在HTTP响应后选择填充列表

angular js select list selected populate after http response

本文关键字:选择 填充 列表 响应 js HTTP Angular      更新时间:2023-09-26

我有一个选择列表,需要根据http响应中的对象默认为某个值:

<select ng-model="isRentVals.cur" ng-options="v for v in isRentVals.values"></select>

响应中的对象名为my_property:

function editPropController($scope, $http) {
    $scope.my_property;
    $http.get('/api/propertyById/' + $scope.prop_id)
        .success(function(properties) {
            $scope.my_property = properties[0];
            $scope.isRentVals = { "cur" : $scope.my_property.is_rented, "values" : ["true", "false"]};
        })
        .error(function(err) {
            alert('We got an error: ' + err);
        });

$http调用的响应将在select元素绑定到isRentVals.cur之后出现。isRentVals还没有定义(将在几毫秒后的成功回调中定义),angular插入一个空val然后绑定。我该如何解决这个问题?

该值默认为空白,我必须重置my_property。

$http调用的响应将在select元素绑定到isRentVals.cur之后出现。因为isRentVals还没有定义(将在几毫秒后的成功回调中定义),所以angular会在select元素中插入一个空项,以便能够绑定到isRentVals.cur的当前值。为了得到更好的答案,你应该创建一个活塞。

像这样初始化isRentVals:

$scope.isRentVals = {}; //initialize as object

并在数据加载时覆盖模型:

function editPropController($scope, $http) {
$scope.my_property;
$scope.isRentVals = {};
$http.get('/api/propertyById/' + $scope.prop_id)
    .success(function(properties) {
        $scope.my_property = properties[0];
        $scope.isRentVals = { "cur" : $scope.my_property.is_rented, "values" : ["true", "false"]};
    })
    .error(function(err) {
        alert('We got an error: ' + err);
    });