I wrote a custom directive to implement a button toggle. When I interact with the button and confirm that I want to toggle it, I get Uncaught Reference Error: on is not defined. I thought that I defined on as an HTML attribute in the custom <button-toggle></button-toggle> element. The reason for my concern is because I may want to send the value of on or off to the server. Where am I going wrong?
buttonToggle.html
<div class="btn-group btn-toggle">
<button class="btn btn-sm" ng-class="{'btn-success':on, 'btn-default':!on}">ON</button>
<button class="btn btn-sm" ng-class="{'btn-danger':off, 'btn-default':!off}">OFF</button>
</div>
buttonToggle.js
angular
.module('myApp')
.directive('buttonToggle', buttonToggle);
function buttonToggle() {
function link(scope, elm, attr, ctrl){
angular.element(elm).on('click', function(){
var confirmResponse = (window.confirm("Are you sure?") === true);
if( confirmResponse ) {
scope.on = !scope.on;
scope.off = !scope.off;
scope.$digest();
if(on)
return off;
else if(off)
return on;
}
scope.$digest();
});
}
var directive = {
restrict: 'AE',
link: link,
replace: true,
templateUrl: 'buttonToggle.html',
scope: {
on: "=",
off: "="
}
};
return directive;
}
buttonToggleCtrl.js
angular.module('myApp').controller('buttonToggleCtrl', buttonToggleCtrl);
function buttonToggleCtrl($scope) {
$scope.activeOn = true;
$scope.activeOff = false;
}
index.html snippet
<button-toggle on="activeOn" off="activeOff"></button-toggle>
As a note, don't worry about how the button looks right now. I know it's messed up in the plnkr, but it looks fine in my app since I'm using Bootstrap there and not in the plnkr. Pay attention to the error being throw in the JavaScript console.
elminangular.element()... it's already done when passed tolink. Can just doelm.on('click'..