ng-click in指令不调用控制器范围中定义的函数

时间:2016-01-20 17:31:11

标签: javascript angularjs

当我点击四个按钮中的一个按钮时,一切似乎都正常呈现但我的ng-click="check($event)"没有触发。我甚至在check($event)函数中添加了警报,但它没有出现。继承人的代码http://codepen.io/theMugician/pen/MKOzzV?editors=101

simonApp.directive('pads', ['lightIt', 'soundIt', function(lightIt,soundIt) {
    var template = '';
  template += '<button ng-click="check($event)" id=' + '{{index}} ' + 'class="pad pad-' + '{{color}}' + '">';
  template += '<div class="ripple js-ripple">';
  template += '<span class="ripple-circle ' + 'ripple-' + '{{color}}' + '"></span></div>';
  template += '</button>';
  return {
    restrict: 'E',
    replace: true,
    scope: {
      color: '@color',
      index: '@index'
    },
    link: function(scope, element, attrs) {
      scope.createRipple = function(e){
        lightIt.createRipple(e, this);
      } 
      //scope.$emit('index', scope.index);
      /*
      var index = parseInt(scope.index);
      scope.playSound = function() {
        soundIt(1);
      }*/
      console.log("scope.index: " + scope.index);
      //console.log("scope.playSound: " + scope.playSound);

      element.on('click', scope.createRipple);
      //element.on('animationend', scope.endRipple);
    },
    template: template
  };
  }]);

这是控制器中的check()函数

  $scope.check = function(e) {
    alert("check works");
    var id = e.currentTarget.id; 
    if($scope.init){
      if(sequence[turn] === id){
        turn++;
        if(turn === sequence.length){
          $scope.step++;
          setTimeout(function(){
            newRound();
          }, 1000);
        }
      }else{
        if($scope.isStrict){
          setTimeout(function(){
            alert('game over');
          $scope.reset();  
          }, 300);
        }else{
          $scope.displaySeq(sequence);
        }
      }  
    } 
  }

1 个答案:

答案 0 :(得分:2)

你不能从那样的指令中调用控制器方法。

如果您需要范围隔离,则必须使用表达式绑定(&#39;&amp;&#39;范围参数)或一起关闭范围隔离(从指令定义中删除scope键)

请参阅John Lindquist的优秀video,例如使用范围表达式绑定。

&#13;
&#13;
    var app = angular.module('app', [])

    app.directive("pads", function() {
    return {
        restrict: "E",
        scope: {
            check: "&"
        },
        template: '<div class="button" ng-click="check({message: value})">click</div></div>',
        link: function(scope) {
          scope.value = 'message to controller'
        }
    };
    });

    app.controller('myCtrl', function() {

       this.doCheck = function(message) {
         alert(message) // alerts "message to controller"
 
       }

    })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='myCtrl as ctrl'>
    <pads check="ctrl.doCheck(message)"></pads>
</div>
&#13;
&#13;
&#13;

相关问题