$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)