gpt4 book ai didi

javascript - Angularjs selectize 指令,$digest 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:34:03 26 4
gpt4 key购买 nike

我在指令内部使用 watch 以及名为 selectize 的第 3 方插件时遇到问题。

我已经阅读了很多关于 $digest/$watch 的内容,但我仍然遇到问题。

我下面的示例“有效”,但我试图防止 $digest already in progress 错误。

可能有更好的方法来解决这个问题,我只是不确定如何。

plunker:http://plnkr.co/edit/3JjTsEU2BlxPWHtw6HaW?p=preview

app.directive('selectize', function($parse) {
return {
restrict: 'A',
require: ['ngModel'],
scope: {
ngModel: '=',
options: '='
},
link: function(scope, el, attrs) {

var $select = el.selectize({
valueField: 'id',
labelField: 'name'
});

var selectize = $select[0].selectize;

// add options
angular.forEach('options', function(tag) {
selectize.addOption(tag);
});

scope.$watchCollection('options', function(newTags, oldTags) {

// why are these the same objects?
console.log('newTags', newTags);
console.log('oldTags', oldTags);

if (newTags !== oldTags) {
// clear options
selectize.clear();
selectize.clearOptions();

// add options
angular.forEach(newTags, function(tag) {
selectize.addOption(tag);
});
}

});

// if value changes without selecting an option,
// set the option to the new model val
scope.$watch('ngModel', function(val) {
console.log('val', val);
// selectize.setValue(val);
});
}
};
});

最佳答案

尝试将对第 3 方的调用包装在 $timeout 内,如下所示:

$timeout(function() {
// clear options
selectize.clear();
selectize.clearOptions();

// add options
angular.forEach(newTags, function(tag) {
selectize.addOption(tag);
});

}, 0);

并且不要忘记注入(inject) $timeout。

在超时为零的情况下(将默认值也保留为 0……),我相信这可以保证在下一个摘要循环中运行,从而防止已经在进行中的错误。如果这是正确的,请有人插话,但我已经使用这个技巧来解决调用某些第三方 (tinyMce) javascript 函数时的摘要错误。

请参阅 betaorbust 在这篇 SO 帖子中的解释:AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

关于javascript - Angularjs selectize 指令,$digest 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22001768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com