Jason Bourne Jason Bourne - 4 months ago 18
AngularJS Question

Rails/Angular JS: Ngclick not appearing to work

I'm creating a simple angular app in my rails app to show a list of registered users. The goal will eventually be to just loop through all of the users and select a random one, update their attribute of "winner" to "true", and update on the DOM next to their name or perhaps an alert to show the winner is.

I created a new test function "showPool" to just see if ngClick is working, but it doesn't seem to be working at all (I.E. click the buttons and they do nothing). Can anyone see what I might be missing?

HTML:

<% if user_signed_in? && current_user.role == "Admin" %>

<h1 class="center">Winner Raffler</h1>
<h4 class="center">To select a winner for this year's scholarship, simply click "choose winner" below</h4>

<div ng-controller="rafflerController">
<ul>
<li ng-repeat="user in users">
{{"Applicant Name:" + " " + user.first_name + " " + user.last_name + " " + "Winner?" + user.winner}}
<span ng-show="user.winner">Winner</span>
</li>
</ul>

</div>
<button ng-click="drawWinner()">Draw Winner</button><br>
<button ng-click="showPool()">Show List of Potential Winners </button>
<% end %>


Javascript File:

//Pool of Winners
var pool = [];

var rafflerApp = angular.module('rafflerApp', ["ngResource"]);

rafflerApp.controller('rafflerController', function($scope, $resource) {
User = $resource("/users.json", {id: "@id"}, {update: {method: "GET", isArray:true}})
$scope.users = User.query()

//Show User Pool List
$scope.showPool = function() {
if (pool.length === 0) {
alert("There are currently no available users in pool.");
} else {
alert("There are currently" + pool.length + " potential winners in the user pool.");
}
}

//Draw a New Winner
$scope.drawWinner = function(){
angular.forEach($scope.users,function(user){
if(!user.winner){
pool.push(user) ;
}
});
if(pool.length >0) {
user = pool[Math.floor(Math.random()*pool.length)];
user.winner = true;
$scope.lastWinner = user;
}
}

});

Answer

You need to place your buttons within the scope of your div that you initiate the rafflerController controller with:

  <div ng-controller="rafflerController"> 
    <ul>
        <li ng-repeat="user in users">
            {{"Applicant Name:" + " " + user.first_name + " " + user.last_name + " " + "Winner?" + user.winner}}
            <span ng-show="user.winner">Winner</span>
        </li>
    </ul>
//YOUR CODE GOES HERE INSTEAD
<button ng-click="drawWinner()">Draw Winner</button><br>
<button ng-click="showPool()">Show List of Potential Winners</button>

</div>