0

I embed search results directly into a HTML page to save a round trip. Currently I do the following:

<script>
  var embeddedResults = { /* rendered by server */ };

  var app = angular.module("MyApp", []);
  app.controller("MyController", ["$scope", function($scope) {
    $scope.results = embeddedResults;
    // ...
  }]);
</script>

What is the proper way of doing this? Also: does this way allow me to put the embeddedResults variable at the very end of the page i.e., even after the controller definition?

3
  • Why do you want to put embeddedResults at the bottom of the page? If you are rendering from the server, I don't see a reason to do the assignment directly in the controller body e.g. $scope.results = { /* rendered by server */ };. If you want your controller to fully load before the results are assigned, you could use $timeout e.g. $timeout(function() { $scope.results = { /* rendered by server */ }; }) Commented Jul 27, 2015 at 18:55
  • I want to inject the results array to be able to 1) test the controller more easily and 2) put the controller and embeddedResults variable into different files. Commented Jul 27, 2015 at 18:59
  • I'd just use a service. Commented Jul 27, 2015 at 20:45

2 Answers 2

1

Method 1 - global using $window

<script>
  var embeddedResults = { /* rendered by server */ };

  var app = angular.module("MyApp", []);
  app.controller("MyController", ["$scope", "$window", function($scope, $window) {
    $scope.results = $window.embeddedResults; // using $window will enable you to mock it in tests
    // ...
  }]);
</script>

Method 2 - constant/value

<script>  
  var app = angular.module("MyApp", []);
  app.constant('embeddedResults', { /* rendered by server */ }); // can also be value
  app.controller("MyController", ["$scope", "embeddedResults", function($scope, embeddedResults) {
    $scope.results = embeddedResults;
    // ...
  }]);
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Seems like a simple service should give you what you are looking for:

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

myApp.service('myService', function() {
    var person = { name: 'Arnold' }; //returned from the server

    this.getPerson = function(foo){
        return person;
    }
});

function MyCtrl($scope, myService) {
    $scope.person = myService.getPerson();
}

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.