将变量从指令传递给控制器

时间:2015-10-13 15:17:16

标签: angularjs

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

答案 0 :(得分:1)

您的指令引入了隔离范围,因此指令scope.something与控制器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

相关问题