Reputation: 10679
I'm writing a web application that will mainly use AngularJS for its modularity and testability and ASP.NET MVC server side technologies for model validation.
The idea is to load PartialView
s in ng-view
s in order to asynchronously load only specific logic parts. So the question is: how to better pass server-side objects to AngularJS controllers? A silly hack that comes to mind is to print things in the PartialView
such as:
window.myValue = 42;
and then get it back from the controller with the $window
service injected:
$scope.myValue = $window.myValue
This is not feasible, though, as ng-view
loadings strip out every <script>
tag before inserting the partial content into the DOM.
I have noticed that there is the ng-init
directive, should I rely on that one alone? Generally speaking, what are the best practices for making these two parts work with each other?
Thanks.
Upvotes: 2
Views: 8759
Reputation: 10679
I ended up using the ng-init
directive.
Luckily, I got to restructure the Web application and go for a single page, client-side, application based on Web services only.
Upvotes: 1
Reputation: 18339
If you are unable to use a REST service (best option) you can easily do exactly what you suggest in your question but perhaps in more modular way. You can encode your view's model and place it in a global variable and then have a service that pulls this out:
Here is an example:
<body ng-controller="MainCtrl">
<div>ID: {{data.id}}</div>
<div>Name: {{data.name}}</div>
<script type='text/javascript'>
// mystuff = @Html.Raw(Json.Encode(Model)); Encode the model to json
mystuff = { id: 1, name: 'the name'};
</script>
</body>
app.controller('MainCtrl', function($scope, DataService) {
$scope.data = DataService.getData('mystuff');
});
app.factory('DataService', function($window) {
var service = {}
service.getData = function(data) {
if ($window[data] !== undefined)
return $window[data];
else
return undefined;
}
return service;
});
Demo: http://plnkr.co/edit/jqm2uT3kbDm2U30MCf48?p=preview
You'd might want to create a standardized model that you use in all of your pages. This is a bit hacky and a REST service is your best option as others have stated.
Upvotes: 1