0

I am working with Angular JS and Yii2. In one of my PHP controllers I need to pass an array of data from backend to front end, so I am json encoding my php array and setting a var in the view like so:

$script = "var projects = '".json_encode($projects)."';";
$this->view->registerJs($script, View::POS_END);

Then in my Angular controller I am getting the JSON data like so:

app.controller('ProjectsController', ['$scope', function($scope, args){
   $scope.projects;    

   $scope.init = function(){
       $scope.projects = angular.fromJson(projects);
   };

   $scope.init();
}]);

My question is, is this good form? Is there a right/wrong way to process data like this on page load with Angular?

Cheers

Ash

5
  • $script = "var projects = ".json_encode($projects).";";...$scope.projects = projects; Commented Feb 5, 2015 at 21:17
  • I am talking more about using an init method to set up data in my controller like that. Musa your amend to the code doesn't work - you can't use repeatables if json isn't imported properly. Commented Feb 5, 2015 at 21:38
  • if you don't use fromJson then you are just setting $scope.projects as a string not an array Commented Feb 5, 2015 at 22:55
  • You probably didn't notice the quotes are around json_encode is no longer there. Commented Feb 5, 2015 at 22:57
  • My bad, I didn't notice. Nice approach Commented Feb 5, 2015 at 23:26

1 Answer 1

1

I think you need to do something like this

app.controller('ProjectsController', ['$scope', '$window', function($scope, $window){
   $scope.projects = angular.fromJson($window.projects);

Or use your init function method if you like, the important part is using the $window service.

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

2 Comments

Nope that won't work. I can however strip out the init method and just use a one-liner in the controller which is more elegant. $scope.projects = angular.fromJson(projects);
Maybe it assumes that you have declared variable "projects" in global scope? I.m. window.projects was declared somewhere on page like var projects = "{json}";. But in this case I see no reason to parse JSON - you can just declare variable as object (array or etc)

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.