Michael Phelps
Michael Phelps

Reputation: 3601

To pass a javascript variable to ng-click

My example:

<button ng-click="action()" >Hello World</button>
 Status : <span >{{foo}}</span>
<script>
var status= Math.random()*1000;
</script>

I want to pass a javascript variable status to action(). Is this possible?

function Mycontroller($scope,$window){

    var status = $window.status//works

    $scope.action = function($window){
        //$window -is undefined;
        //var status = $window.status
        debugger
        $scope.foo='default value for foo' + status;

    }

}

Example 2:

window.status= Math.random()*1000;
<button ng-click="action(window.status)" >Hello World</button>

$scope.action = function($status){
        // $status - is undefined ...Why??
    }

Thank you very much.

Upvotes: 0

Views: 1547

Answers (3)

Ben Wilde
Ben Wilde

Reputation: 5672

As JB Nizet said, you cant access the window or other global variables directly in an expression (like the one inside ng-click), only the scope. So window will return undefined in an expression. But, as HarishR said, you can access window in your controller, or a controller method, as his code shows.

But, if you really want to set it and pass it from the view, you can do an ng-init.

<div ng-controller="myController" ng-init="status = 1000">
  <button ng-click="action(status)">Hello World</button>
  Status : <span>{{foo}}</span>
</div>

see plunker: http://plnkr.co/edit/OWsLjAlLB4II2jGaKupN?p=preview

note that u cant access Math in the ng-init expression, as its a global variable but not on the scope.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692231

No, it's not possible. Expressions use variables that are exposed on the scope. They can't access global variables (i.e. attributes of window), unless of course the window itself is exposed on the scope (using action(window.status), provided you have called $scope.window = $window before).

Upvotes: 4

harishr
harishr

Reputation: 18065

try below

$scope.action = function(){
    var status = $window.status
}

you dont need to receive $window in $scope.action...

why are you getting it as undefined is because, you are not passing it from HTML

<button ng-click="action()" >Hello World</button>

and actually you dont need to pass it from html and you are trying to receive it in your controller...

Upvotes: 1

Related Questions