gpt4 book ai didi

javascript - 如何从 Controller 中切换此 notificationDirective 中的 ng-class?

转载 作者:行者123 更新时间:2023-11-29 17:00:43 25 4
gpt4 key购买 nike

http://plnkr.co/edit/I30bgBrsO1Wo3JCcbUmK?p=preview

指令 html 中的 ng 类切换:
ng-class="{true: "main.success", false: "main.error"}

完整的 HTML

<body ng-app="myApp" ng-controller="MainCtrl as main">
<notification-msg></notification-msg>

<button ng-click="main.openAlert('success')">Click for success</button>

<button ng-click="main.openAlert('error')">Click for error</button>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="alert.js"></script>
<script src="script.js"></script>
</body>

主控

(function() {
var app = angular.module('myApp', ['notification-directives'])
.controller('MainCtrl', ['$scope', function($scope) {

var vm = this;

vm.openAlert = function(m) {
console.log(m);
vm.message = m;
vm.notification = m;

// trying to toggle the ng-class in the directive here
if (m === 'success') {
vm.success = true;
} else if (m === 'error') {
vm.error = false;
}
}
}]);
})();

通知指令

(function() {
var app = angular.module('notification-directives', [])
.directive('notificationMsg', function () {

return {
restrict: 'E',
template:
'<section ng-show="main.notification" ' +
'class="ng-notification"> ' +
'<p class="notify-msg">{{main.message}}</p> ' +
'<div class="notify-bg ng-class="{true: "main.success", false: "main.error"} success"></div> ' +
'</section>'
};
});
})();

最佳答案

要在您的 ng-class 中形成一个 if 子句,只需使用

ng-class="main.success?'success':'error'"

Here您的 plunker 是否已修改,以便它可以工作。不幸的是,我不得不添加一个模板文件以使引文更易于阅读。

此外,我删除了您的 vm.error 并在 true 和 false 之间切换 vm.success

关于javascript - 如何从 Controller 中切换此 notificationDirective 中的 ng-class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28532142/

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