AngularJS指令启用/禁用所有子元素(a,按钮)

时间:2016-01-11 08:16:07

标签: javascript jquery angularjs twitter-bootstrap angular-directive

考虑以下HTML

<div userLevel="100">
    <a href="/someSite"></a>//should be disabled
    <button type="button">Click me</button>//should be disabled
    <button type="button" ng-disabled="true">Can't click me</button>//maybe already disabled
</div>

当我的当前用户级别是&lt; 100应禁用所有链接或按钮的子元素。这可以通过添加classname和attribute "disabled"来完成(根据Bootstrap 3)。

$element.find("a, button").toggleClass("disabled", true).prop("disabled", true);

但我怎么能处理已被禁用的子元素?我如何处理子元素的ng-disabled指令,这些指令依赖于除用户级别之外的任何其他内容?启用时,我必须从仅由我的指令禁用的元素中删除禁用的类/ attr,而保留其他禁用的元素。我怎么能做到这一点?

这是我到目前为止所做的:

.directive("userLevel", [
    "userService",
    function ($USER) {
        return {
            restrict : "A",
            scope : true,
            link : function ($scope, $element, $attr) {

                var m_evtNS = ".userLevel",

                    //the user level needed to access children
                    m_RequiredUserLevel = $scope.$eval($attr["userLevel"]),

                    /**
                     *
                     * @param {Boolean} disable
                     */
                    disable = function (disable) {
                        //remove evt listener and toggle children class/attr
                        $element
                            .off(m_evtNS)
                            .find("a, button")
                            .toggleClass("disabled", disable)
                            .prop("disabled", disable);

                        //show login dialog when clicking on disabled elements
                        if (disable) {
                            $element.on("click" + m_evtNS, function () {
                                $USER.showLoginDialog();
                            });
                        }
                    };

                //watch for changes of the current user level (login/logout)
                $scope.$watch(function () {
                   return $USER.CurrentUser.level;
                }, function (userLevel) {
                   disable(userLevel < m_RequiredUserLevel);
                });
            }
        };
    }
])

0 个答案:

没有答案