我很难搞清楚如何更新单击事件中的值。我有一个自定义指令,基本上是一个按钮开关。当按钮关闭时,我希望它将某个变量的值更改为0.当它打开时,我希望它将该变量的值更改为大于0的数字。将指令中的变量传递给控制器
我创建了一个plnkr重新创建问题。
此外,我读了this post,这是有点帮助,但仍有我挠我的头如何处理我的问题。
在指令中,我处理click事件,然后尝试更改变量的值,但它在视图中从未被更改过。我想我必须将该指令的值传递给控制器,以便将其传播到视图,但我不知道如何去做。
angular
.module('app')
.directive('buttonToggle', buttonToggle);
function buttonToggle() {
function link(scope, elm) {
if(elm === "#btnToggle1") {
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(scope.on) {
$scope.switchBtnOutput = 8044; // var I'm trying to change
return scope.off;
} else if(scope.off) {
$scope.switchBtnOutput = 0; // var I'm trying to change
return scope.on;
}
}
scope.$digest();
});
} else {
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(scope.on) {
return scope.off;
} else if(scope.off) {
return scope.on;
}
}
scope.$digest();
});
}
}
var directive = {
restrict: 'AE',
link: link,
replace: true,
templateUrl: 'buttonToggle.html',
scope: {
on: "=",
off: "="
}
};
return directive;
}