This is the continuation of the last segment where i left the discussion after displaying the static data on the page. However, now let’s try to fetch data from the server itself. so for this i would need to do couple of changes here. Now, since here JSON is going to be passed on over http request. so, am going to take the raw values and pass the same as shown below. So, here am putting whole model into the string.
So, i do need data which is serialized and passed on as JSON to the view. so, here in the real world project i won’t having that View Model Class in here, rather than keeping in a separate repository also, it won’t have any hard coded data as it is there in the controller, rather than making some api call to database and then inject the same.
Now, let’s build and try that. so, you can see that even after that values are not populated in there, so when you see the source of the page, you will see the JSON data which is pushed down in the model is upper case, and we are expecting the same in camelCase, this is because of the default behavior of the JSON serializer which we are using JSON.Net
However, we could change the behavior as shown below with a small setting which is basically a contract resolver for using the Camel case property names.
Now, when i build the same refresh the page , i’ll get the same result as shown below
This was the demonstration that how to bootstrap the data using ng-init and this is fairly useful in many cases, but there is one limitation to this approach that movies variable is only available within the scope of ng-init means any variable inside that particular div will be ok. so, in case if we want to expose the data outside this view, i need to expose the data globally. so, in order to achieve the same i could use controllers. so, let’s go ahead and create one controller
Now, when i refresh the page, i won’t be able to see the values on the page, reason being is incoming values are not in the ng-scope. However, i could verify that values are coming properly in the chrome debugging console section as shown below.
also, i need to add one script in index page as well, that is controller reference as shown below.
so, now when i come and refresh the page, i would see the desired results as shown below
so, now we have AngulardataService which can be used across the app. Now, let’s use the service in our controller as shown below
so, if you refresh the page, you will see that page is still loading and getting the data, only now it’s getting the data from the service instantiated from the page and then injected into the controller and then we set the service data to the scope data from the service. So, i wrap this section here for now. In the next module we’ll see how to communicate with the services asynchronously. so, till then stay tuned and happy coding.
1,489 total views, no views today