2

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?

2
  • What is the error? Is id undefined in the function body? Commented Sep 15, 2016 at 6:18
  • do not use parenthesis {{}} inside your ngController, please provide some more details. Commented Sep 15, 2016 at 6:19

3 Answers 3

5

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

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

1 Comment

Thank you so much for your code, It solved my problem :)
1

Here assuming that you have list of images as array

You have to find out the object from images array based on passed parameter i.e. id.

In your controller

$scope.imgs = [{
    id: 1,
    src1: 'red.jpg',
    src2: 'green.jpg'
}, {
    id: 2,
    src1: 'black.jpg'.
    src2: 'yellow.jpg'
}]

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

Comments

1
$scope.activeimageset = function(id) {
   $scope.listOfObjs; //it is array where all objects are stored
   $scope.dummyAttr; //attr you want to change from object you will get from param
   var requiredObj = ($scope.listOfObjs).filter(function( obj ) {
      return obj.id === id; //returns object with passed id
   });
   $scope.dummyAttr = requiredObj.attr;
}

Hope thats what you were looking for

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.