我构建了一个指令,将 $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)