0

I have a set json object like

var data = {item1: "Hello1",item2:"Hello2",item3:"Hello3",item4:"Hello4",item5:"Hello5"};

I want each item to be available in the scope. Like

$scope.item1
$scope.item2
...

Is it possible in Angular

2 Answers 2

1

You can do something like this:

for (var key in data) {
  $scope[key] = p[key]
}
Sign up to request clarification or add additional context in comments.

Comments

1

Sure you can. get the keys of the object and assign create scope variables like this

angular.module("app",[])
.controller("ctrl",function($scope){
var data = {item1: "Hello1",item2:"Hello2",item3:"Hello3",item4:"Hello4",item5:"Hello5"};

for(var k in data) {
  $scope[k] = data[k]
}

console.log($scope.item1)
console.log($scope.item2)
console.log($scope.item3)

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 
</div>

1 Comment

Thanks sachila.. But you have to make a small correction. $scope[k] = data[k];

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.