Reputation: 689
At my controller's I have created a function that's responsible for initialising the state of the scope. It is then called at ng-init
like so: ... ng-init="init(value)"
where value
is some variable from the global scope. The problem is - it doesn't work. Doesn't angular allow to pass variables? Is anything within ng-init
only evaluated without any context and I have to prepare a string?
Upvotes: 2
Views: 15519
Reputation:
I'm sure this is not the "right" thing to do, but it works and I use it.
Set a global variable on window..
<script type="text/javascript">
window.myCtrlData = {\"a\": \"It's a duck!\"};
</script>
..then pass the name of the variable to your controller using ng-init..
<div ng-controller="MyCtrl" ng-init="init('myCtrlData')">
..then retrieve the global variable inside of init()
function MyCtrl($scope) {
$scope.init = function (dataKey) {
if (dataKey && window[dataKey]) {
var data = window[dataKey];
// add data to scope
angular.extend($scope, data);
}
};
}
Upvotes: 13
Reputation: 689
Ok, posting answer to my own question.
Quick answer: You don't.
ng-init
accepts only variables that are already at the scope. Or you can create one inline. I actually was doing that for a while (passing stringified json variable) but it didn't work well for some data (consider following json: ng-init='"{\"a\": \"It's a duck!\"}'"
)
The proper solution is to create a service that would use and pass global variables. Am not sure if that's much better but I guess it's still better than using globals at the controller.
Upvotes: 0
Reputation: 20189
It does work try replacing value
with "hello"
and you'll see it works, maybe it's something to do with value not being defined, you should try init('{{value}}')
and see what that does if not then you need to find out why value
is not defined.
Upvotes: 0