Angularjs ui-select (select2) 无法使用 'Controller as' 语法未得到 selected ite

Angularjs ui-select (select2) not working with 'Controller as' syntax not getting selected ite

我正在尝试让 select HTML 控件与位于 here on GitHub. For some reason, I am able to get the item selected when using $scope syntax, but not when I use the Controller As syntax. The plunker I am trying to get working with Controller as syntax is located here 的 AngularJS ui-select 一起工作。我不确定我遗漏了什么,特别是因为 $scope 语法完美运行。

我没有收到任何要报告的错误。这是 plunker 中的一个片段。

控制器

var app = angular.module('demo', ['ngSanitize', 'ui.select']);

app.controller("MainCtrl", MainCtrl);

function MainCtrl()
{
  var controller = this;

  controller.person = {};
  controller.people = [
    { name: 'Adam',      email: 'adam@email.com',      age: 10 },
    { name: 'Amalie',    email: 'amalie@email.com',    age: 12 },
    { name: 'Wladimir',  email: 'wladimir@email.com',  age: 30 },
    { name: 'Samantha',  email: 'samantha@email.com',  age: 31 },
    { name: 'Estefanía', email: 'estefanía@email.com', age: 16 },
    { name: 'Natasha',   email: 'natasha@email.com',   age: 54 },
    { name: 'Nicole',    email: 'nicole@email.com',    age: 43 },
    { name: 'Adrian',    email: 'adrian@email.com',    age: 21 }
  ];

}

index.html

<body ng-controller="MainCtrl as vm">
    <h3>Select2 theme</h3>
    <p>Selected: {{vm.person.selected}}</p>
    <ui-select ng-model="person.selected.name" theme="select2" ng-disabled="disabled" style="min-width: 300px;">
    <ui-select-match placeholder="Select a person in the list or search his name/age...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="person in vm.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>

HTML 中用作 controller 别名的名称也应与 Javascript 文件中引用的变量名称相同。另外,您缺少方法 MainCtrl() 中的范围。 所以在这里,在你的例子中,JS 中的变量应该是 vm。您可以参考 jsfiddle.

中的示例

请在下面找到更新后的代码。

Javascript

function MainCtrl($scope) {
    var vm = this;

    vm.person = {};
    vm.people = [
      { name: 'Adam', email: 'adam@email.com', age: 10 },
      { name: 'Amalie', email: 'amalie@email.com', age: 12 },
      { name: 'Wladimir', email: 'wladimir@email.com', age: 30 },
      { name: 'Samantha', email: 'samantha@email.com', age: 31 },
      { name: 'Estefanía', email: 'estefanía@email.com', age: 16 },
      { name: 'Natasha', email: 'natasha@email.com', age: 54 },
      { name: 'Nicole', email: 'nicole@email.com', age: 43 },
      { name: 'Adrian', email: 'adrian@email.com', age: 21 }
    ];
    $scope = vm;
}

修复所有脚本以使用 https 而不是 http(plunker 的要求)并将 ng-model="person.selected.name" 更改为 ng-model="vm.person.selected.name" 后,ControllerAs 版本完美运行没有进一步的调整。

https://plnkr.co/edit/2VtUefWPKdBVaqY1gU66?p=preview