gpt4 book ai didi

javascript - 将jquery插件应用于angularJS ng-repeat中的新项目

转载 作者:行者123 更新时间:2023-11-30 17:44:19 25 4
gpt4 key购买 nike

您好,我有一个使用 angular 进行渲染的小部件和一个 jquery bootstrap 插件来切换复选框。

<div class="notification" ng-repeat="notification in notifications">
<textarea ng-model="notification.text">
<div class="make-switch" data-on="success" data-off="danger">
<input type="checkbox" ng-model="notification.status">
</div>
</div>
<button ng-click="addNotification()">Add</button>

在页面加载时首次呈现时一切正常,但当我添加新通知时,插件未应用。这符合逻辑。

var myAppModule = angular.module('myApp', []);
myAppModule.controller('NotificationController',function($scope,$timeout) {
$scope.notifications = [
{
text:'text1.',
status: true
},
{
text:'Text2',
status: false
}
];

$scope.addNotification = function(){
var notification = {
text: "",
status: true
}
$scope.notifications.push(notification);
$timeout(function(){
$('.notification:last() .make-switch').bootstrapSwitch();
})
}
});

所以我使用 $timeout 和 jquery ":last()"选择器将插件应用到最后一项。

它是正确的吗?一切正常,但看起来不太好。

最佳答案

这是一个很好的指令候选者。查看 Angular Directive(指令)的更详细解释 here .当你必须以某种方式修改 DOM 时,你应该在指令中进行。 Controller 访问和修改 DOM 被认为是一种不好的做法,它应该与范围一起工作。

所以在你的情况下你可以创建一个简单的指令

directive('notificationSwitch', function () {
return {
restrict: 'A',
link: function(scope, element) {
element.bootstrapSwitch();
}
};
});

在您的 View 中,您可以像这样使用此指令

<div notification-switch data-on="success" data-off="danger">

这样每次使用此指令添加新项目时,都会调用应用 bootstrapSwitch 的链接函数

关于javascript - 将jquery插件应用于angularJS ng-repeat中的新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20416668/

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