在控制器中更改范围变量不会在视图中更改变量

时间:2014-10-27 23:18:29

标签: javascript angularjs angular-ngmodel ui-select2 angularjs-select2

我正在使用带有AngularJS的Select2,我想更改与控制器中的选择框关联的ng模型。目前在我的plunkr示例中,每当我更新ng-model时,select2框都会清除,就像我将ng-model重置为空数组一样。如何设置它以便我可以先添加一个人,然后在控制器中启动一个功能以向选择框添加更多选择,然后在框中查看原始选择和新选择?

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: 'nicole@email.com',    age: 43, country: 'Colombia' }]);
  };

  $scope.person = {};
  $scope.people = [
    { name: 'Adam',      email: 'adam@email.com',      age: 12, country: 'United States' },
    { name: 'Amalie',    email: 'amalie@email.com',    age: 12, country: 'Argentina' },
    { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
    { name: 'Adrian',    email: 'adrian@email.com',    age: 21, country: 'Ecuador' },
    { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30, country: 'Ecuador' },
    { name: 'Samantha',  email: 'samantha@email.com',  age: 30, country: 'United States' },
    { name: 'Nicole',    email: 'nicole@email.com',    age: 43, country: 'Colombia' },
    { name: 'Natasha',   email: 'natasha@email.com',   age: 54, country: 'Ecuador' },
    { name: 'Michael',   email: 'michael@email.com',   age: 15, country: 'Colombia' },
    { name: 'Nicolás',   email: 'nicolas@email.com',    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>

1 个答案:

答案 0 :(得分:0)

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

这种固定的矿井。我认为watch函数调用$ scope。$ apply绑定新值。我尝试使用$ scope。$ apply哪个有效,但它引发了一个错误。

希望有所帮助

相关问题