AngularJS使用从服务器接收的数据预先选择一个选项

时间:2019-03-06 07:40:00

标签: angularjs

我已经用AngularJS创建了CRUD,在更新部分中,当涉及到选择时,我无法获得预选的值。文本字段显示正确的数据,我能够无错误地更新所有字段。请理解我是一个初学者。下面粘贴的代码很重要。并预先感谢。

HTML

<div ng-init="readLangs()" class="md-block">
    <select 
        ng-model="lang_id" 
        ng-options="lang.lang_name for lang in langs">
    </select>
</div>

JS

$scope.showUpdateChnForm = function(chn_id){

// get chn to be edited
chnsFactory.readOneChn(chn_id).then(function successCallback(response){

    // put the values in form
    $scope.chn_id = response.data.chn_id;
    $scope.chn_name = response.data.chn_name;
    $scope.chn_price = response.data.chn_price;
    $scope.lang_id = response.data.lang_id;
    }
}

readOneChn将输出lang_id和lang_name

{
"chn_id":"2",
"chn_name":"BBC World News",
"chn_price":"1.00",
"lang_id":"1",
"lang_name":"English"
}

从服务器中检索选择选项 JS

$scope.readLangs = function(){
// use chns factory
chnsFactory.readLangs().then(function successCallback(response){
    $scope.langs = response.data.records;
}, function errorCallback(response){
    $scope.showToast("Unable to read record.");
});
}

2 个答案:

答案 0 :(得分:1)

感谢@Anurag,我已经解决了这个问题。 如您对ng-model所述,我更改了lang,但是不需要过滤器。必须有一个track by。我记得另一种要求使用track by的解决方案,但它对我没有用。由于@Anurag's solution,我学会了$scope.lang = {lang_id: response.data.lang_id},现在,如果我添加了track by lang.lang_id,它就可以了。

HTML

<div ng-init="readLangs()" class="md-block">
    <select ng-model="lang"
            ng-options="lang.lang_name for lang in langs track by lang.lang_id">    
    </select>
</div>

JS

$scope.showUpdateChnForm = function(chn_id){
    // get chn to be edited
    chnsFactory.readOneChn(chn_id).then(function successCallback(response){
        // put the values in form

        $scope.chn_id = response.data.chn_id;
        $scope.chn_name = response.data.chn_name;
        $scope.chn_price = response.data.chn_price;
        $scope.lang = {lang_id: response.data.lang_id};
    }
}

答案 1 :(得分:0)

您应该在html中使用

<div ng-init="readLangs()" class="md-block">
    <select 
        ng-model="lang" 
        ng-options="lang.lang_name for lang in langs">
    </select>
</div>

在JS中:

$scope.showUpdateChnForm = function(chn_id){    
    chnsFactory.readOneChn(chn_id).then(function successCallback(response){

        // put the values in form
        $scope.chn_id = response.data.chn_id;
        $scope.chn_name = response.data.chn_name;
        $scope.chn_price = response.data.chn_price;

        // Update $scope.lang
        $scope.lang = $filter('filter')($scope.langs, {lang_id: response.data.lang_id})[0];
    }
}

然后,您可以根据需要使用$scope.lang.lang_id