如何从控制器内切换此 notificationDirective 中的 ng-class?

How to toggle ng-class in this notificationDirective from within the Controller?

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

指令中的 ng-class 切换 html:
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

如果整个部分应该有背景色,您可以使用

class="ng-notification  {{main.message}}" 

因为 main.message 中的字符串等于您要添加的 类。

然后你可以用 main.openAlert(' ') 隐藏,如果你使用

ng-show="(main.message)"

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

有几件事可以使这项工作

查看example

首先使用1个变量来判断失败或成功,在我的例子中我使用了'success',成功时为真,错误时为假

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

  vm.success = (m === 'success');
}

第二个在您的指令中更改 ng-class 位置和 ng-class 字符串

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

大功告成!