I'm trying to pass a scope into a function and I can't seem to get it to work correctly. Here's what I have -
ng-click="clickFunction(scope1)"
//the function
$scope.clickFunction = function(passedScope){
passedScope = false;
console.log($scope.scope1);
So - it's prett straight forward I just want to pass in the scope and set it to false in this click. When I log the scope after changing it hwever it still says it's true. I also tried -
$scope.passedScope
What I am trying to do is set $scope.scope1 = false. It is set in the top of the controller as true and controls a button nearby by that button having ng-disabled="!scope1", I cant just do a scope1 =!scope! on the click because it goes through a modal to confirm the user wants to complete then runs a modalInstance.result.then(function () { there I then need to set the passed scope to false. I would just call the scope directly, but I'm trying to make a function which I can use across multiple delete functions, thus trying to pass he scope that needs changing to false.
I was thinking I could just pass the scope through the function.
Thanks!
update According to what @Josep showed me today I was able to make a work around by passing the scope as a string like so
ng-click="clickFunction('scope1')"
and then doing
$scope[passedScope] = false;
If you want to pass the current scope of a part of your view to a function, the way to do it would be:
ng-click="clickFunction(this)"
But then in your function you should be treating that scope like this:
$scope.clickFunction = function(passedScope){
passedScope.somePropertyOfTheScope = false;//<---Notice the difference with the code that you are suggesting.
You can't set the scope
to false
, you can set one of its properties to false
, but not the scope itself. That wouldn't make any sense because scope
is an object that holds a set of properties, events and functions. Some of them inherited from its scope ancestors up to $rootScope
, and some of them are custom.
Maybe what you are trying to do is to pass one of the properties of the scope
as a parameter of a function, so that you can change it in that function. However, in javascript the only way to pass a parameter by reference is to pass the object and update one of its properties, if you pass a boolean property to the function, then you will be passing the value of that boolean property, not the reference. Please have a look at this: Pass Variables by Reference in Javascript.
As an alternative to Josep's answer (which helped me find it out), you could simply call like this:
ng-click="clickFunction()"
And then in your function you can refer the current scope with this
:
$scope.clickFunction = function() {
this.somePropertyOfTheScope = false;
//...
}
This is very useful when using ng-include
that creates a new scope, so clickFunction
is actually at parent scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With