nackolysis nackolysis - 3 months ago 28
AngularJS Question

passing javascript variable to ng-click event in angular js

I want to pass Javascript variables to

ng-click
event in angular js but am getting null values.

Below is my javascript variables that needs to be passed to angular js

<script>

var userid = localStorage.getItem("userid");
var uName = localStorage.getItem("name");
var uage = localStorage.getItem("age");


<script>


Below is my angular js controller

<script>
app1 = angular.module('app1');

app1.controller('mainCtrl',
['$scope', '$rootScope', function ($scope, $rootScope) {

console.log("Data okay");

}]);

<script>


Here is how am passing the variables to
NG-CLICK
events

<li ng-show=" ap in parkers | filter:{ name: uname } " id="userid" ng-click="connect(userid,uname,uage)">
</li>


How can I accomplished that and ensure it will be working. Thanks

VSO VSO
Answer

Your variables need to be attached to the controller's $scope. Delete your variables and add $scope variables like below:

app1.controller('mainCtrl',
        ['$scope', '$rootScope', function ($scope, $rootScope) {

       console.log("Data okay");
       $scope.userid = localStorage.getItem("userid");
       $scope.uName = localStorage.getItem("name");
       $scope.uage = localStorage.getItem("age");
       $scope.connect = function(userId, uName, uAge){
           console.log('It worked!'); 
       }

}]);

Note that the connect function also needs to be attached to the $scope to be called via ng-click.

Comments