There seems to be no way to provide data to an Angular controller other than through attributes in the DOM handled by directives (of which ngInit
is a handy example).
I'd like to provide other "constructor" data, e.g. objects with functions to my
$scope
.
Background: We have an existing dashboard-style single page application,
where each widget manages a <div>
, and widget-instance-specific data
is provided as an object along with support functions, etc.. This object data
doesn't fit nicely into DOM attributes or ngInit
calls.
I can't really come up with a better way to it than to have a global hash, and use an instance-specific unique key. Before calling angular.bootstrap(domElement, ['myApp'])
, we set up all "constructor" parameters in this global hash under the key and then use
<div ng-init='readInitialValuesFromHash("uniqueKey")'>...</div>
where readInitialValuesFromHash
gets all its data from
globalHash["uniqueKey"]
and stores what it needs it in $scope
(possibly
just the "uniqueKey"
).
(What seems like an alternative is to use a directive and jQuery.data()
, but jQuery.data
uses a global hash behind the scenes)
Of course I can hide the global data in a function, but fundamentally still use a singleton/global variable. This "global hash and pass key as param to ng init trick" just seems like such a hack...
Am I missing something? Is there a better way, given that the widget-instance-specific data is actually more complicated than suitable for inserting in the DOM via directives/attributes due to the legacy dashboard framework?
Are there dangers when putting complicated objects in the $scope
as long as they aren't referenced by directives, {{}}
or $scope.$watch()
calls?
Angular's front page says:
Add as much or as little of AngularJS to an existing page as you like
So in light of that, how should I proceed?
EDIT: Comments have asked to make my question more clear. As an example of a non-trivial constructor parameter, assume I want to give this myObj
to the controller, prototypical inheritance, function and all:
var proto = {
p1: "p1",
pf: function() {
return "proto"
}
};
function MyObj(ost) {
this.ost = ost;
}
MyObj.prototype=proto;
var myObj = new MyObj("OST");
So I have myObj, and I have a string:
<div ng-app='myApp' ng-controller="MyCtrl">....</div>
I put the string in the DOM, and call angular.bootstrap()
.
How to I get the real myObj
object into MyCtrl
's $scope
for this <div>
, not a serialized/deserialized version/copy of it?