service portal how to get data from server to client

sam1212
Mega Expert

Hi All,

This looks simple but i am unable to figure out

i am getting the data from server to client but i unable to access the variable outside the function

here i am getting the watchlist from server and keeping in $scope.ta1 but if i try to keep outside the function i am not able to access

spUtil.update($scope).then(function(data){

              $scope.ta1=data.watchlistValues[0].name;

alert($scope.ta1);//working good

});

alert($scope.ta1);//not working

Any help is appreciated.

11 REPLIES 11

sam1212
Mega Expert

Hi Nath,



Even i tried that it does not work. This is more of   a issue where ajax call is done but the value is not available out of function.


If you define a variable inside a function, it is only available in that function. If you use a variable that was defined outside that function then you can update the variable within the function, and the variable will also be available outside the function. That's how scopes work in JavaScript. That's why I suggested you use c.data since that is already defined if you use the "controller as" functionality with "var c = this".



For further reading on JavaScript scopes you can check out: http://ryanmorr.com/understanding-scope-and-context-in-javascript/


Hi Nath,



the issue is not about the scope it is more about the asynchronous call.. by the time i am getting the result from server the next time after the function is getting executed and it saving the undefined value.


On the server side you have:



        data.watchlistValues=[];



This is going to wipe out whatever is in that array every time the server script is run



Perhaps you want to do something like:



        if (!input) {


                  data.watchlistValues=[];


        }


fschuster
ServiceNow Employee
ServiceNow Employee

Sam, it is very hard to debug this if we can't see all pieces of the widget, i.e. if $scope is injected, spUtil. You also seem to use the ngTagsInput dependency - did you make sure this is working properly?



Could you attach screens of your HTML, Client & Server part? That might help to get you on the right track.



Other than that I can only second what Nathan said, stick to using the controller as notation, meaning "c.myVariable" if you are only using it within the view and/or controller or using "c.data.myVariable", in case you need the variable value in the Server Script.



//Edit: good catch Nathan, that looks like it might be it. @Sam: also make sure to configure your query properly, the "active" field is a bool but you are providing a string value though.