2015-10-13 171 views
0

我很难搞清楚如何更新单击事件中的值。我有一个自定义指令,基本上是一个按钮开关。当按钮关闭时,我希望它将某个变量的值更改为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; 
} 

回答

1

您的指令引入了隔离范围,所以指令scope.something与controller scope.something不同。只有你在范围中声明的变量:{...}被绑定。

顺便说一下,这些指令需要返工: 1.您可以在模板中使用ng-click - 这将让您不要使用废话摘要调用。 2. on ==!off - 所以用一个变量代替2. 3. $ scope = {} < <这是干嘛的。

所以,新的模板:

<div class="btn-group btn-toggle"> 
    <button class="btn btn-sm" ng-class="{'btn-success':on, 'btn-default':!on}" ng-click="toggle()" ng-disabled="on">ON</button> 
    <button class="btn btn-sm" ng-class="{'btn-danger':!on, 'btn-default':on}" ng-click="toggle()" ng-disabled="!on">OFF</button> 
</div> 

指令:

function buttonToggle() 
{ 
    function link(scope, elm) 
    { 
    scope.toggle = function() { 
     var confirmResponse = (window.confirm("Are you sure?") === true); 

     if(confirmResponse) { 
      scope.on = !scope.on; 
      scope.output = scope.output + 'Changed to ' + scope.on + '. '; 
     } 
    } 
    } 

    var directive = 
    { 
     restrict: 'AE', 
     link: link, 
      replace: true, 
     templateUrl: 'buttonToggle.html', 
     scope: { 
      on: "=", 
      output: '=' 
     } 
    }; 

    return directive; 
} 

普拉克http://plnkr.co/edit/qK8TMmjoxQ7rgKraryKp?p=preview

编辑工作:

这里是fixed plnk from the OP

相关问题