javascript - How to display player turn in AngularJS? -


beginner programmer here. in controller constructor have:

vm.turncounter = 0; vm.turn = getturn();  function getturn() {             if (vm.turncounter % 2 == 0) {                 return 'player 1';             } else {                 return 'player 2';             }         } 

vm capture variable, i'm not using $scope. i'm trying display current turn in view {{ctrl.turn}} far changes in vm.turncounter has no effect on {{ctrl.turn}}, displays "player 1". missing angular databinding concepts here? thanks.

here's whole controller, omitted super long getboards() because it's long array i'll put in firebase:

(function () {     angular         .module('app')         .controller('tictactoectrl', tictactoectrl);      function tictactoectrl() {         var vm = this;          vm.addpiece = addpiece;         vm.boards = getboards();         vm.turncounter = 0; //encapsulate         vm.turn = 'player 1';         vm.getturn = getturn();          function addpiece(obj) {             if (obj.p1 || obj.p2)                 obj.p1 = true;             vm.turncounter++;         }          function getturn() {             if (vm.turncounter % 2 == 0) {                 return 'player 1';             } else {                 return 'player 2';             }         }     } })(); 

here simplified answer: http://jsfiddle.net/jd96d6kr/

in order view know going on going have use $scope. whole point of data binding in angular. change var vm $scope.vm

<body ng-app="app"> <div ng-controller="tictactoectrl">     <button ng-click="next()">next</button>     turn {{vm.turn}} </div> 

(function() {   angular   .module('app',[])   .controller('tictactoectrl', function($scope)   {     $scope.vm = this;     $scope.vm.addpiece = $scope.addpiece;     $scope.vm.turncounter = 0;     $scope.vm.turn = 'player 1';      $scope.addpiece = function(obj)     {       if (obj.p1 || obj.p2)         obj.p1 = true;       $scope.vm.turncounter++;     }      $scope.getturn = function()     {       console.log($scope.vm.turncounter);       return ($scope.vm.turncounter % 2 == 0) ? 'player 1' : 'player 2';     }      $scope.next = function()     {       $scope.vm.turncounter++;       $scope.vm.turn = $scope.getturn();     }   }); })(); 

i'm not sure addpiece() does, didn't that.


Comments

Popular posts from this blog

How to group boxplot outliers in gnuplot -

cakephp - simple blog with croogo -

bash - Performing variable substitution in a string -