1

我正在使用Select2和AngularJS,我想更改與控制器中選擇框關聯的ng模型。目前在我的plunkr示例中,每當我更新ng模型時,select2框都會清除,就像我將ng模型重置爲空數組一樣。我如何設置它,以便我可以先添加一個人,然後在控制器中啓動一個功能,將更多選擇添加到選擇框中,然後在框中查看原始選擇和新選擇?更改控制器中的作用域變量不會更改視圖中的變量

Plunkr

JS控制器

app.controller('DemoCtrl', function($scope, $http, $timeout) { 
    $scope.addSomePeeps = function() { 
    var peeps = angular.copy($scope.multipleDemo.selectedPeople) 

    $scope.multipleDemo.selectedPeople = peeps.concat([{ name: 'Nicolás', email: '[email protected]', age: 43, country: 'Colombia' }]); 
    }; 

    $scope.person = {}; 
    $scope.people = [ 
    { name: 'Adam',  email: '[email protected]',  age: 12, country: 'United States' }, 
    { name: 'Amalie', email: '[email protected]', age: 12, country: 'Argentina' }, 
    { name: 'Estefanía', email: '[email protected]', age: 21, country: 'Argentina' }, 
    { name: 'Adrian', email: '[email protected]', age: 21, country: 'Ecuador' }, 
    { name: 'Wladimir', email: '[email protected]', age: 30, country: 'Ecuador' }, 
    { name: 'Samantha', email: '[email protected]', age: 30, country: 'United States' }, 
    { name: 'Nicole', email: '[email protected]', age: 43, country: 'Colombia' }, 
    { name: 'Natasha', email: '[email protected]', age: 54, country: 'Ecuador' }, 
    { name: 'Michael', email: '[email protected]', age: 15, country: 'Colombia' }, 
    { name: 'Nicolás', email: '[email protected]', age: 43, country: 'Colombia' } 
    ]; 

    $scope.multipleDemo = {}; 
    $scope.multipleDemo.selectedPeople = [$scope.people[5], $scope.people[4]]; 

}); 

HTML

<body ng-controller="DemoCtrl"> 

    <h3>Array of objects</h3> 
    <ui-select multiple ng-model="multipleDemo.selectedPeople" theme="select2" ng-disabled="disabled" style="width: 800px;"> 
    <ui-select-match placeholder="Select person...">{{$item.name}} &lt;{{$item.email}}&gt;</ui-select-match> 
    <ui-select-choices repeat="person in people | propsFilter: {name: $select.search, age: $select.search}"> 
     <div ng-bind-html="person.name | highlight: $select.search"></div> 
     <small> 
     email: {{person.email}} 
     age: <span ng-bind-html="''+person.age | highlight: $select.search"></span> 
     </small> 
    </ui-select-choices> 
    </ui-select> 
    <p>Selected: {{multipleDemo.selectedPeople}}</p> 

    <button ng-click="addSomePeeps()">Click me to add some specific peeps</button> 

</body> 

回答

0
$scope.$watch('multipleDemo',function(newValue,oldValue){ 
       console.log("WATCH IN PROGRESS: "+newValue+" "+ oldValue); 
      }); 

這種固定我的。我認爲watch函數調用$ scope。$ apply來綁定新的值。我嘗試使用$範圍。$應用哪些工作,但它拋出了一個錯誤。

希望可以幫到