Ale*_*ull 5 javascript html5 angularjs jquery-chosen
我已将所选插件集成到我的angularjs应用程序中.我的app.js看起来像这样.
myApp.directive('chosen', function() {
var linker = function (scope, element, attr) {
scope.$watch('countriesList', function() {
$('#countries').trigger('chosen:updated');
console.log('I acctuallty get in here');
})
element.chosen();
};
return {
restrict: 'A',
link: linker
};
})
Run Code Online (Sandbox Code Playgroud)
我的选择看起来像这样
<div class="control-group">
<label for ="countries" class="control-label">Countries: </label>
<div class="controls">
<select chosen ng-model="countries" id="countries" ng-options="country.name for country in countriesList" data-placeholder="Select Countries" multiple class="span chzn-select"></select>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
问题是当页面首次加载时,选择中不显示任何内容.检查元素时有选项.
这chosen:updated
似乎没有用.我把console.log()
它放在手表里,它正在开火.如果我.trigger('chosen:updated')
在浏览器中运行它可以很好地工作.我确实尝试过,element.trigger
但那也没用.真令人沮丧!
在调用之前,您需要让Angular(实际上是浏览器)正确地呈现选择chosen
.您可以使用setTimeout
或Angular 来完成此操作$timeout
.
app.directive('chosen', function($timeout) {
var linker = function(scope, element, attr) {
$timeout(function () {
element.chosen();
}, 0, false);
};
return {
restrict: 'A',
link: linker
};
});
Run Code Online (Sandbox Code Playgroud)
第三个参数false
可以防止不必要的摘要循环.
演示: http ://plnkr.co/edit/9Afq65uatTjnb4J6ICcB?p=preview
如果您需要动态添加或删除项目,这将有效:
app.directive('chosen', function($timeout) {
var linker = function(scope, element, attr) {
scope.$watch('countriesList', function() {
$timeout(function() {
element.trigger('chosen:updated');
}, 0, false);
}, true);
$timeout(function() {
element.chosen();
}, 0, false);
};
return {
restrict: 'A',
link: linker
};
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://plnkr.co/edit/rEBu6d3HtaNhThWidB5h?p=preview
请注意,默认情况下$watch
使用引用相等性来确定是否执行侦听器.如果向数组添加项,则变量countriesList
仍将引用相同的数组,因此不会执行侦听器.
true
传递给的第三个参数$watch
使得它使用angular.equals
而不是引用相等.
归档时间: |
|
查看次数: |
6552 次 |
最近记录: |