gpt4 book ai didi

javascript - 选择的 Angular 指令不会更新

转载 作者:数据小太阳 更新时间:2023-10-29 04:08:13 25 4
gpt4 key购买 nike

我已经按照这个很棒的教程 (link) 学习了 Chosen 和 Angular(代码几乎相同)

这是我的指令:

app.angularModule.directive('chosen', function() {
var linker = function (scope, element, attrs) {
var list = attrs['chosen'];

scope.$watch(list, function () {
element.trigger('chosen:updated');
});

element.chosen({ width: '350px'});
};

return {
restrict: 'A',
link: linker
};
});

这是 html:

<select data-placeholder="Choose a Category"  multiple class="col-lg-8 chosen-select" chosen="items"
ng-options="item._backingStore.Name for item in items" ng-model="selectedCategories" >
</select>

我想要的是,当用户点击编辑按钮时,模态窗口弹出,并且在点击编辑按钮之前选择的类别在模态窗口中被选中。

这是 Controller 的一部分:

  $scope.$watch(function() { return adminCrudService.getCategoriesForUpdate(); }, function() {
$scope.action = "edit";
$scope.categoriesForUpdate = adminCrudService.getCategoriesForUpdate();
if ($scope.categoriesForUpdate.length > null) {
$scope.selectedCategories = _.filter($scope.items, function (item) {
return _.contains($scope.categoriesForUpdate, item);
});
}
});

我已经记录了 $scope.selectedCategories,它们一切正常,但由于某种原因,在 chosen 中没有选择任何内容。

那么我做错了什么,我该如何解决?

编辑

我注意到当我选择一些项目时,关闭模态,再次打开它,尽管我将这一行放在 $watch 中,但选定的值又在那里了

$scope.selectedCategories = "";

编辑 2

所以我暂时搁置了这个问题,因为我有更重要的事情要处理。我试过没有选择,即使用“正常”选择和代码工作。因此,我选择的指令显然无法正常工作。

最佳答案

我已经解决了,该解决方案实际上非常简单明了(当您了解 Angular 指令的工作原理时)。这是指令的完整代码:

app.angularModule.directive('chosen', function() {
var linker = function (scope, element, attrs) {
var list = attrs['chosen'];

scope.$watch(list, function () {
element.trigger('chosen:updated');
});

scope.$watch(attrs['ngModel'], function() {
element.trigger('chosen:updated');
});

element.chosen({ width: '350px'});
};

return {
restrict: 'A',
link: linker
};
});

关于javascript - 选择的 Angular 指令不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18262442/

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