AngularJS: Select not 2-way binding to model

后端 未结 2 1870
天涯浪人
天涯浪人 2021-01-31 02:11

I am using a select to show Client names. A user should be able to select an existing client, which will then update the scope property:

Controller

相关标签:
2条回答
  • 2021-01-31 02:59

    I think you are probably using a child scope and don't know it. ng-if, ng-repeat, ng-switch and ng-include all create child scopes. Values on your scope are inherited, but if you change the value in a child scope it sets a value on the child scope and leaves the inherited value unchanged on the parent. Try using an object instead to hold your values and see if that fixes it. Since you are only setting a property on an object and not a value directly on the scope it will use the parent scope's inherited object and update the value.

    $scope.data = {
        existingClient: $scope.clients.length > 0 ? $scope.clients[0] : undefined
    };
    

    View:

    <select ng-model="data.existingClient" 
            ng-options="client.name for client in clients">
    </select>
    

    You can use the AngularJS Batarang extension in chrome to help debug your scopes.

    0 讨论(0)
  • 2021-01-31 02:59

    This is also a solution to keep parameters into your $scope object:

    controller:

    $scope.scope = $scope;
    $scope.clients = [];
    $scope.existingClient = $scope.clients.length > 0 ? $scope.clients[0] : undefined;
    

    view:

    <select ng-model="scope.existingClient" ng-options="client.name for client in clients"></select>
    
    0 讨论(0)
提交回复
热议问题