AngularJS - Hide/Show directive output based on expression
angularjs, angularjs-directive
Solution
If I'm understanding what you want to do, the easiest way would be with an `ng-show`. Then you don't even need the `$watch` (or the link function for that matter)
app.directive('searched', function(){
return {
restrict: 'E',
replace: true,
scope: {
keywords: '=ngModel'
},
template: '<span ng-show="keywords.length > 0"><span class="field">You searched for:</span> {{ keywords }}</span> '
};
});
Updated fiddle
Problem
I'm wanting to output some markup from a custom Directive, but only if the model contains some text. I'm almost there, but I'm just not quite sure how to turn the template on/off when the model changes, and if this is even the most efficient way of doing it. Here is the markup: ``` <div data-ng-controller="test"> <div class="box"> <input type="text" id="search" maxlength="75" data-ng-model="keywords" /> </div> <searched data-ng-model="keywords"></searched> </div> ``` The JS: ``` var app = angular.module('myApp', []); app.directive('searched', function(){ return { restrict: 'E', replace: true, scope: { keywords: '=ngModel' }, template: '<span><span class="field">You searched for:</span> {{ keywords }}</span> ', link: function(scope, element, attrs) { scope.$watch('keywords', function(newVal, oldVal){ if(newVal === null) { // Output nothing! } else { // Output Template as normal. } }, true); } }; }); app.controller("test", ['$scope', function($scope) { $scope.keywords = null; }]); ``` And an example JSFiddle