在使用Angular单击时向主体添加弹出窗口(然后删除)

时间:2014-09-09 17:06:46

标签: angularjs

我正试图围绕Angular中的指令概念。

我想在点击链接时显示模态框。模态框的内容是动态的。在jQuery中,它将是一个简单的$("body").append(myModal),然后在关闭时从DOM中简单地remove()

现在我想在纯Angular中做同样的事情。这就是我到目前为止所做的:

控制器功能:

$scope.userLogout = function() {
    notification.show();
};

服务:

.service('notification', ['$rootScope',
    function($rootScope) {
        var notification = {
            open: false,
            show : function() {
                this.open = true;
            },
            hide: function() {
                this.open = false;
            }
        };
        return notification;
    }
])

指令:

.directive('notification', ['notification',
    function(notification){
        return {
            restrict: 'E',
            replace: true,
            template: (notification.open) ? '<div class="myModal"></div>' : ''
        }
}])

当我的服务中的值发生变化时,如何更新指令?或者这是正确的方法吗?

1 个答案:

答案 0 :(得分:1)

对于它的价值,使用像Angular这样的东西,可以简单地在类似于模态的元素上使用data-ng-showdata-ng-hide。根据您的使用情况,您可能不需要创建指令来实现您想要的功能。请考虑以下事项:

HTML:

...
<div data-ng-show="notification.open" class="modalPopup">
    ...
    {{notification.my_modal_message}}
    ...
    <button data-ng-click="closeModal()">Close</button>
</div>

JS(简化):

function myCtrl ($scope) {
    $scope.notification = {
        my_modal_message: "Bender's back, baby!",
        open: false
    }

    $scope.logout = function () {
        // logout stuff
        logout().success(function () {
            // open the modal
            $scope.notification.open = true;
        }
    }

    $scope.close = function () {
        $scope.notification.open = false;
    }
}

有时,制定一个完整的指令来为你做这样的事情要好得多。但是,再次 - 根据您的使用情况 - 这可能就是您所需要的。请记住一些事情。

相关问题