Reputation: 4727
I have been trying to figure this out and did some searches but the results I find always seem to address issues that happen between directives and controllers.
I have a problem within a directive. I think I am not understanding scope correctly.
I have a directive that looks like this:
mb.directive("plainText", function() {
return {
restrict: 'E',
scope: {
value: "@",
},
templateUrl: 'plainText.html',
link: function(scope, element, attrs){
scope.view = false;
element.bind("click", function() {
if ( scope.view == false ) {
scope.view = true;
console.log(scope.view);
} else {
scope.view = false;
console.log(scope.view);
}
})
scope.value = attrs.value;
}
}
})
and a HTML template like this:
<div>{{value}}</div> // this part of the directive always stays visible
<div ng-show="{{view}}"> // THIS LINE NEEDS TO RESPOND TO THE CLICK
<input type="text" ng-model="value">
<br/>
<div class="btn btn-default" ng-click="save()">Save</div>
<div class="btn btn-default" ng-click="cancel()">Cancel</div>
</div>
My console log shows that the click event is being fired by the scope value but "view" is not being applied to the div that needs to show and hide.
Could someone explain what I am doing wrong?
Upvotes: 2
Views: 8303
Reputation: 388446
The template should be just
<div ng-show="view">
<input type="text" ng-model="value">
<br/>
<div class="btn btn-default" ng-click="save()">Save</div>
<div class="btn btn-default" ng-click="cancel()">Cancel</div>
</div>
the ng-show directive watches for the changes in the scope variable passed via the attribute so you need to pass the scope variable name instead of the variable by interpolating it.
Also you need to call scope.$apply() in the jQuery click handler
element.bind("click", function () {
scope.view = !scope.view;
console.log(scope.view);
if (!scope.$$phase && !scope.$root.$$phase) {
scope.$apply()
}
})
Demo: Fiddle
Upvotes: 1