Angularjs 是否通过角度控制器更新select2?
我试图使用Angular的$http指令从服务器中提取标记列表,并使用该列表填充select2 select。我的代码如下所示:Angularjs 是否通过角度控制器更新select2?,angularjs,jquery-select2,angular-ui,angularjs-select2,Angularjs,Jquery Select2,Angular Ui,Angularjs Select2,我试图使用Angular的$http指令从服务器中提取标记列表,并使用该列表填充select2 select。我的代码如下所示: var samplePage = angular.module('samplePage', ['ui.select2']); samplePage.controller('sampleController', function($scope, $http) { console.log($scope); // THIS
var samplePage = angular.module('samplePage', ['ui.select2']);
samplePage.controller('sampleController', function($scope, $http) {
console.log($scope);
// THIS WORKS
$scope.tags = ['a', 'b', 'c'];
$http.get('angular.html').success(function(rc) {
console.log($scope);
// THIS DOES NOT WORK
$scope.tags = ['d', 'e', 'f'];
})
});
angular.bootstrap(document, ['samplePage']);
<div ng-app="samplePage">
<div ng-controller="sampleController">
<input id="tags" ui-select2="{tags:tags, simple_tags: true}" multiple ng-model="myTags" style="width: 150px;">
<p>$scope.tags = {{tags}}<p>
</div>
</div>
但是,“标签”没有更新!或者,更确切地说,“标签”正在更新,但select2小部件似乎没有正确绑定
视图如下所示:
var samplePage = angular.module('samplePage', ['ui.select2']);
samplePage.controller('sampleController', function($scope, $http) {
console.log($scope);
// THIS WORKS
$scope.tags = ['a', 'b', 'c'];
$http.get('angular.html').success(function(rc) {
console.log($scope);
// THIS DOES NOT WORK
$scope.tags = ['d', 'e', 'f'];
})
});
angular.bootstrap(document, ['samplePage']);
<div ng-app="samplePage">
<div ng-controller="sampleController">
<input id="tags" ui-select2="{tags:tags, simple_tags: true}" multiple ng-model="myTags" style="width: 150px;">
<p>$scope.tags = {{tags}}<p>
</div>
</div>
$scope.tags={{tags}}
以下是完整测试应用程序的要点:
我是否未正确使用select2模块?或者模块本身有缺陷吗?ng model指令应该是将填充select输入的
$scope
。改用ng model=“tags”
编辑
当你有
<input id="tags" ui-select2="{tags:tags, simple_tags: true}" multiple ng-model="myTags" style="width: 150px;">
ui-select2=“{tags:tags,simple_tags:true}”中的tags
指的是要在下拉列表中显示为选项的模型,而ng model=“myTags”
中的myTags
指的是所选的选项
如果希望在加载列表时选择一些选项,请在控制器中将它们设置为$scope.myTags
。这通常应该是选项的子集(即,$scope.tags
此处)。这很有用!但不完全是这样:当我将代码改为ng model=“tags”
时,下拉菜单的选项仍然是['a','b','c']
。从理论上讲,如果绑定正确的话,该列表不应该再存在于任何地方。类似地,['d','e','f']
永远不会作为选项出现(即使我取消选择它们)。@poundifdef您正在当前页面上执行get请求。将其替换为要从中加载的源,它将消失,即a、b、c。