http://plnkr.co/edit/I30bgBrsO1Wo3JCcbUmK?p=preview
指令 html 中的 ng-class 切换:
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/