簡體   English   中英

angularjs ng-model和ng-select奇怪的行為

[英]angularjs ng-model and ng-select strange behaviour

我有要綁定到select元素的人員對象列表。

控制器實現:

// Person controller
function PersonCtrl($scope) {
    $scope.persons = [{id: 1, name: 'alex'}, {id: 2, name: 'jhon'}];
    $scope.selectedPerson = {id: 2, name: 'jhon'};  
}

HTML標記:

 <select ng-model="selectedPerson" ng-options="p.name for p in persons"></select>

問題在於,綁定似乎僅從HTML到作用域起作用,而反之則不行。 如果我從下拉菜單中選擇一項,它將正確更新$ scope.selectedPerson。 但是,如果我最初將$ scope.selectedPerson變量的值設置為人員列表中的對象之一,則該值將不會反映在選擇控件上。

我也有小提琴,確切地顯示了問題所在: http//jsfiddle.net/nE3gt/

先感謝您!

將其設置為要綁定到的數組的索引:

$scope.selectedPerson = $scope.persons[0];

演示: http//jsfiddle.net/nE3gt/3/

您需要將selectedPerson設置為persons數組中的元素,而不是新對象-否則Angular不知道它們是同一件事。

// Person controller
function PersonCtrl($scope) {

$scope.persons = [{id: 1, name: 'alexx'}, {id: 2, name: 'jhon'}];

$scope.selectedPerson = $scope.persons[1];

$scope.submit = function () {
    //console.log(JSON.stringify($scope.Person));
    $("#obj").text(JSON.stringify($scope.Person));
};

}

更新的小提琴: http : //jsfiddle.net/nE3gt/2/

編輯

如果我對您的理解正確,那么您可以按照以下方式做一些事情:

// Person controller
function PersonCtrl($scope) {

    //serverData is the result of some http request...
    var serverData = {persons: [{id: 1, name: 'alexx'}, {id: 2, name: 'jhon'}], selectedPerson: {id: 2, name: 'jhon'}};

    $scope.persons = serverData.persons;
    $scope.selectedPerson = null;

    //find obj in persons that equals selectedPerson
    for(var i = 0, l = serverData.persons.length; i < l; i++)
    {
        if(serverData.persons[i].id === serverData.selectedPerson.id)
        {
            $scope.selectedPerson = serverData.persons[i];
        }
    }

    $scope.submit = function () {
        //console.log(JSON.stringify($scope.Person));
        $("#obj").text(JSON.stringify($scope.Person));
    };
};

即使您的數據作為不同的對象返回,也需要確保將selectedPerson設置為person數組中的項目。

新提琴: http : //jsfiddle.net/nE3gt/4/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM