2

I've been trying to create a generic function in angular that changes a $scope parameters value.

I've been wondering why I cannot pass $scope.var as an argument to a function e.g.:

webApp.controller ('VotesCtrl', function ($scope) {
    $scope.param = 42;

    change($scope.param);
    function change(contextParam) {
      contextParam = (Math.random()*100)+1;
    };
});

When I ran this function $scope.param remains 42.

Is there an alternative besides:

webApp.controller ('VotesCtrl', function ($scope) {
    $scope.param = 42;

    change('param');
    function change(contextParam) {
      $scope[contextParam] = (Math.random()*100)+1;
    };
});

My Plunk

3
  • 1
    What is the underlying problem you're trying to solve? Commented Mar 19, 2014 at 15:38
  • To understand why plnkr.co/edit/9996W3Io4KewA3tgokQR?p=preview is not working. And if the solution I gave is the only way Commented Mar 19, 2014 at 15:41
  • I would avoid passing around scoped Items like this, if you need to pass it into a function I would define it locally and pass that in. If you wanted to change the scoped value then you could just call the scoped item inside the function without a need to pass it in. Commented Mar 19, 2014 at 15:42

1 Answer 1

6

The short answer is "Don't bind to primitive values". See http://stsc3000.github.io/blog/2013/10/26/a-tale-of-frankenstein-and-binding-to-service-values-in-angular-dot-js/

var webApp = angular.module('webApp', []);

//controllers
webApp.controller ('VotesCtrl', function ($scope) {
    $scope.param = { value: 42 };

    change($scope.param);
    function change(contextParam) {
      contextParam.value = (Math.random()*100)+1;
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Or you pass the entire $scope object to the function instead. Not keen on passing scope or its attributes around, so either option is not great imo.

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.