0

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.

1
  • it is undefined because in ng-click="action()" you are not specifying any parameters... check my answer Commented Jul 25, 2014 at 15:36

3 Answers 3

4

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).

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

Comments

2

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.

Comments

1

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...

Comments

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.