user6767148 user6767148 - 4 months ago 16
HTML Question

select angularjs variable using function parameter

I've some function like this:

$scope.activeimageset = function(id){}

Now, I pass some parameter as ID to mentioned function, and I want to select some variable using gathered parameter, something like this:

$scope.activeimageset = function(id){$scope.img{{id}}.src1 = $scope.img{{id}}.src2;}

That's mean I want to select some object using parameter passed to my function and then I set one of the attributes of that object to another attribute. How can I do that? I know my code is wrong and doesn't work, but I want to know how can I make it work?


You can rewrite your function like this:

$scope.activeimageset = function(id){
  $scope['img' + id].src1 = $scope['img' + id].src2;

In JS you can use two ways to obtain properties values, they are Dot Notation and Square Bracket Notation.

Here is the very basic example of using these ways:

var obj = {
 prop1: 'prop1 value',
 prop2: [1,2,3]

var propName = 'prop2';

console.log(obj.prop1); // 'prop1 value'
console.log(obj[propName]); '[1, 2, 3]'

In summary:

  • Dot notation is faster to write and clearer to read.

  • Square bracket notation allows access to properties containing
    special characters and selection of properties using variables (just like in your case).