-1

How to serialize the ViewModel ($scope) in AngularJS? I'm planning to store the serialized value to a ASP.NET server-side div to persists across postbacks.

3 Answers 3

1

$scope is an object created by AngularJS to interact with the markup. It can contain methods that can be referenced from html. You can create a simple JavaScript object for storing and transferring data and keep it in your scope.

$scope.model = { name : 'my model' };
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, this gave me an idea. By grouping all of my viewstate variables into a single object, I would just need to specify the parent object in the serializer. Instead of $scope.var1=[];$scope.var2=[];, use $scope.var={var1:[],var2:[]};.
0

Not sure if you should serialize the whole $scope (actually, you shouldn't - it's a complex object. You should only care about persisting your own data).

Use:

angular.toJson($scope.YourData);

obviously, there's a method-companion fromJson: http://docs-angularjs-org-dev.appspot.com/api/angular.fromJson

1 Comment

You're right I shouldn't serialize the whole $scope.
0

I am not sure about how your ASP.Net application is structured, but here are some of my inputs.

If you plan to do postbacks with ASP.Net I would suggest you to rethink you client side framework. AngularJS and many such similar frameworks are not meant for working with postback model. Typically what happens when you use frameworks like AngularJS

  • The server based on the request, sends HTML content (initial view) to client browser
  • The browser renders the view.
  • The client side Javascript frameworks kick in provide the necessary functionality

From this point onwards there is no post back, most of the functionality is achieved using AJAX requests, which does not cause a browser refresh. If a navigate is performed from one page to another the process described above is repeated again.

As you can see postbacks are not natural to this setup, and any effort to bolt these two model together would produce less than optimum results.

1 Comment

Hi Chandermani, our ASP.NET application works through postbacks, automatic AJAX (through UpdatePanels) and just recently we've added AngularJS in the mix. Its an old huge application and we don't have the time to recode all of its parts to use AngularJS+AJAX so we're trying to upgrade some portions of the page by mixing technologies. We were able to mix the techs but for Angular, we had to manually specify every variable in the viewmodel ($scope) to the serializer. We we're looking for a shortcut/an easier way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.