0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just an addition:The difference here is $scope (named for obvious reason) scopes the value to the controller it is defined in, and binds that value to the view. var will not bind to template views, so it's not accessible in ng-click/show etc
Agree with all that 100%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.