抓取$(this)元素的html并插入$ scope.variable

时间:2015-11-15 21:12:59

标签: javascript jquery html angularjs

我正在尝试使用buttons获取.html() html并插入$scope.player。该按钮正在使用choosePlayer()调用ng-click函数,但它无效。

这里是codepen链接:http://codepen.io/theMugician/pen/ojJrRp

HTML

<body ng-app="ticTacToe" ng-controller="MainCtrl">

<div class="container">
  <div class="row">
    <div class="col-xs-12 text-center">
      <h1>TIC TAC TOE</h1>
    </div>
  </div>
</div>

<div id="wrapper" class="container text-center">
  <div class="row">
    <div ng-click="move(cell)" ng-repeat="cell in cells" class="col-xs-4 square text-center">
      {{cell.value}}
    </div>
  </div>

</div>
<div class="container">
  <div class="row text-center">
    <h1>CHOOSE A SHAPE</h1>
    <button ng-click="choosePlayer()" class="btn btn-red" id="choose-cross">✖</button>
    <button ng-click="choosePlayer()" class="btn btn-green" id="choose-circle">&#9711;</button>
  </div>
</div>
</body>

JAVASCRIPT

var app = angular.module("ticTacToe", []);
app.controller("MainCtrl", function($scope){
  var cell = $(".square");
  $scope.player = "";
  var cross = "×";
  var circle = "◯";

  $scope.choosePlayer = function(){
    $scope.player = $(this).html();
  }

  $scope.cells = [ { value: '' }, { value: '' }, { value: '' }, 
     { value: '' }, { value: '' }, { value: '' } ,
    { value: '' }, { value: '' }, { value: '' }  
  ];

  $scope.move = function(cell){
    cell.value = $scope.player;
  };

});

1 个答案:

答案 0 :(得分:2)

您可以在ng-click()指令中传递$event object

<button ng-click="choosePlayer($event)" class="btn btn-red" id="choose-cross">✖</button>
<button ng-click="choosePlayer($event)" class="btn btn-green" id="choose-circle">&#9711;</button>

然后访问event.currentTarget以获取控制器中的元素:

Updated Example

没有jQuery:

$scope.choosePlayer = function(e) {
  $scope.player = e.currentTarget.innerText;
}

使用jQuery:

$scope.choosePlayer = function(e) {
  $scope.player = $(e.currentTarget).text();
}