简体   繁体   English

http响应后填充角度js选择列表

[英]angular js select list selected populate after http response

I have a select list that needs to default to a certain value based on an object from an http response: 我有一个选择列表,该列表需要基于http响应中的对象默认为特定值:

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

The object from the response is called my_property: 响应中的对象称为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);
        });

The response from the $http call will come after the select element is bound to isRentVals.cur. 在select元素绑定到isRentVals.cur之后,来自$ http调用的响应将出现。 isRentVals is not defined yet (will be defined in in the success callback in some milliseconds later) angular inserts an empty val then binds. isRentVals尚未定义(将在几毫秒后在成功回调中定义),角度插入一个空val,然后绑定。 How can I work around this? 我该如何解决?

The value is defaulted to blank and I have to reset my_property.is_rented in an ng_click method to save the new values. 该值默认为空白,我必须在ng_click方法中重置my_property.is_rented以保存新值。

The response for your $http call will come after your select element is bound to isRentVals.cur. $ http调用的响应将在您的select元素绑定到isRentVals.cur之后。 Because isRentVals is not defined yet (will be defined in in your success call back in some milliseconds later) then angular insert an empty item to your select element to be able to bind to current value of isRentVals.cur. 因为isRentVals尚未定义(将在几毫秒后在您的成功调用中定义),然后将空项目插入您的select元素,以便能够绑定到isRentVals.cur的当前值。 Also for better answers you should create a plunker. 此外,为了获得更好的答案,您应该创建一个塞子。

Initialize isRentVals like this: 像这样初始化isRentVals

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

and overwrite the model when the data loaded: 并在加载数据时覆盖模型:

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);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM