2016-09-15 36 views
2

選擇angularjs變量我有一些像這樣的功能:使用函數參數

$scope.activeimageset = function(id){} 

現在,我通過一些參數作爲ID所提到的功能,我想用收集的參數,像這樣的東西,選擇一些變量:

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

這意味着我要選擇使用傳遞給我的函數參數的一些對象,然後我把這個對象的另一個屬性的屬性之一。我怎樣才能做到這一點?我知道我的代碼是錯誤的,不起作用,但我想知道我該如何使它工作?

+0

什麼是錯誤?函數體中'id'未定義? – SayusiAndo

+0

請勿在您的ngController中使用圓括號「{{}}」,請提供一些詳細信息。 –

回答

5

你可以重寫你的函數是這樣的:

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

在JS,你可以用兩種方式來獲得屬性的值,它們是Dot Notation and Square Bracket Notation

Here is使用這些方法的非常簡單的例子:

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]' 

總結:

  • 點標記更快編寫和更清晰的閱讀。

  • 方括號表示法允許訪問包含
    特殊字符和使用變量選擇屬性(就像你的情況一樣)。

+1

非常感謝你的代碼,它解決了我的問題:) – user6767148

1

這裏假設你有圖像的列表作爲數組

我們根據您傳遞的參數即ID找出從圖像陣列的對象。

在你的控制器

$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; 
} 
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; 
} 

希望那是什麼你要找的