Reputation: 1385
I have a problem to show and hide a div from a template on HTML page. here is a simple JSFiddle example Example.
app.directive('example', function () {
return {
restrict: 'E',
template: '<button ng-click=\"clickMe()\">Click me</button>',
scope: {
exampleAttr: '@'
},
link: function (scope) {
scope.clickMe = function () {
scope.showMe = !scope.showMe;
};
}
};
});
and the HTML is like that :
<body ng-app="demo" ng-controller="exampleController">
<div>
<div ng-controller="exampleController as ctrl">
<example example-attr="xxx">
<p ng-show="showMe">Text to show</p>
</example>
</div>
</div>
I cant add my html code to the template like in this example because my div that i want to show or hide is an entire html page.
app.directive('example', function () {
return {
restrict: 'E',
template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>',
scope: {
exampleAttr: '@'
},
link: function (scope) {
scope.clickMe = function () {
scope.showMe = !scope.showMe;
};
}
};
});
Thanks in advance
Upvotes: 3
Views: 299
Reputation: 67171
You need to use transclusion
if you want to have something within your <example> <!-- this stuff here --> </example>
, show up once the directive is compiled and created.
Get ride of the scope: {}
object within your directive.
app.directive('example', function () {
return {
restrict: 'E',
template: '<div ng-transclude></div><button ng-click="clickMe()">Click me</button>',
// ^ notice the ng-transclude here, you can place this wherever
//you want that HTML to show up
// scope : {}, <-- remove this
transclude: true, // <--- transclusion
// transclude is a "fancy" word for, put those things that are
// located inside the directive html inside of the template
//at a given location
link: function (scope) {
/* this remains the same */
}
};
});
This will have it working as intended!
Side note: You don't need to escape
\"
your double quotes since you have your template inside of asingle quote ' <html here> '
string.
Upvotes: 3
Reputation: 12813
You could do it like this - Fiddle
JS
var app = angular.module("demo", [])
app.controller('exampleController', function ($scope) {
$scope.showMe = false;
});
app.directive('example', function () {
return {
restrict: 'E',
template: '<button ng-click="clickMe()">Click me</button><br>',
scope: {
exampleAttr: '@',
showMe: "="
},
link: function (scope) {
scope.clickMe = function() {
scope.showMe = !scope.showMe;
};
}
};
});
Markup
<body ng-app="demo" ng-controller="exampleController">
<div>
<div ng-controller="exampleController as ctrl">
<example example-attr="xxx" show-me="showMe"></example>
<p ng-show="showMe">Text to show</p>
</div>
</div>
</body>
Upvotes: 2