Reputation: 3159
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;
};
});
Upvotes: 2
Views: 5266
Reputation: 39277
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;
};
});
Upvotes: 6