我已经建立了将$ rootScope.showContent值更改为true或false的指令。

然后我使用ng-show =“ showContent”来隐藏或显示元素。

这种方法效果很好,但我想避免使用$ rootScope以及scope.apply()函数的使用。
你能建议我一个更好的方法吗?

在下面,您将找到一些代码:

的HTML

<body ng-app="myApp">
    <div ng-controller="AppCtr">
        <hide-amounts ></hide-amounts>

        <div ng-show="showContent">
            <h1>Hello from h1</h1>
            <p>Hello from paragarapsh</p>
        </div>
         <div ng-show="showContent">
            <h1>Hello from h1</h1>
            <p>Hello from paragarapsh</p>
        </div>
    </div>
</body>


角度的

var myApp = angular.module('myApp', []);

myApp.run(function ($rootScope) {
    $rootScope.showContent = true;
})

myApp.controller("AppCtr", function ($scope) {

})
.directive('hideAmounts',["$rootScope", function ($rootScope) {
    return {
        restrict: "E",
        replace: true,
        template: '<a href="#">Hide Content</a>',
        link: function (scope, element, attrs) {
            element.click(function () {
                scope.$apply(function () {
                    $rootScope.showContent = !$rootScope.showContent;
                })
                return false;
            })
        }
    };
}]);


jsfiddle链接:http://jsfiddle.net/RickyStam/AkVzz/(jsfiddle无法正常工作不知道为什么:P)

最佳答案

老实说,定义指令只是在父控制器上切换标志不是一个好主意

只是使用

<button ng-click="showContent = !showContent ">


代替。

但是,如果您真的想摆脱$ rootScope,可以:

1)将参数传递给指令jsfiddle

 <hide-amounts show="showAmounts" ></hide-amounts>

var myApp = angular.module('myApp', []);

myApp.controller("AppCtr", function ($scope) {
    $scope.obj = {};
    $scope.obj.showAmounts = true;
    $scope.showAmounts = true;
})
.directive('hideAmounts',["$rootScope", function ($rootScope) {
    return {
        restrict: "E",
        replace: true,
        scope: {show:'='},
        template: '<a href="#">Hide Amounts</a>',
        link: function (scope, element, attrs) {
            element.click(function () {
                scope.$apply(function () {
                    scope.show = !scope.show;
                })
                return false;
            })
        }
    };
}]);


2)通过调用指令中的$ scope.emit('message',param)并在父控制器$ scope.on('message,function(s,param){})上注册侦听器,将消息发送到父控制器

关于javascript - 切换元素可见性的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24484973/

10-12 00:10
查看更多