Get dynamic scope variable value angularjs

痴心易碎 提交于 2019-12-11 19:26:06

问题


I have array of object which contains number of scope variable name in it. All the scope variable value has already been set before.

Something like this :

$scope.myarray = [{'id':'myname1'},{'id':'myname2'}];
$scope.myname1 = 'John';
$scope.myname2 = 'Rick';

Now if I want to get value of the scope variable which within the 'id' of 'myarray',what should I do?
I have already tried this

var getMeMyValue = $scope[myarray[0]];

Something like this,but it didnt help.
I have seen in this example that how to set scope variable dynamically
But I didnt get anything about how to get value dynamically

Please help me with this,Thanks!!

P.S. Here I'm dynamically getting my scope variable so there is no way that I can access them directly to get their value


回答1:


This will get the value for you dynamically:

var getMyValue = $scope[$scope.myarray[0].id];



回答2:


Please check this http://plnkr.co/edit/ZwwuKRVwgD74ufY2GmB8?p=preview

Controller -

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

app.controller('myController', function($scope) {
  $scope.myarray = [{'id':'myname1'},{'id':'myname2'}];
  $scope.myname1 = "John;"
  var getMeMyValue = $scope[$scope.myarray[0].id];
  console.log(getMeMyValue);

});


来源:https://stackoverflow.com/questions/30457851/get-dynamic-scope-variable-value-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!