Wednesday, March 25, 2015

Angular JS: Initializing a controller with a server side run-time value

This problem may look too much difficult for newbies to Angular JS. I was also stucked for some days, googled different websites, but no website could give me any working solution to my problem. Atlast I asked my senior and he helped me to solve this difficult problem in just few minutes.

Problem:

The problem was that I was using multiple partial views on my MVC view. I was trying to use Angular JS for just one of the partial view, whereas, all other views were using server side MVC controller. I had to pass a parameter from server side to my angular JS controller, so that it can get the data based on the parameter.

Solution:

First I tried ngInit approach, but it didn't worked. Every time data function was executing first and then initialize function was executing, as a result undefined parameter was passing to my controller function.

My senior advised me to initialize global variable in javascript on view with the value that I want to pass as a parameter, like this:

//script start

var globalValue = @MyValue;

//script end


then in the angular js controller use this global value like this:

$scope.GetFunctionData(globalValue).then( function() {
.
.
.
}


That's all!

Please write to me whether this solution worked for you. Stay blessed :)

Popular Posts