1

I am very new to AngularJS, please accept my apology if this is an easy question. I also hope that the title of the question is understandable?

I am using AngularJS with ASP.Net MVC application to ready data from SQL server table and then display the data on the view. Everything looks fine but when I try to step forward for more advanced tasks, I find out that I am not able to read the object from Angular module.

For example, I want to read the contact details of a user, each user has different number of contacts. So, the ng-repear limitTo should not be the same. To do that, I wanted to read some data and then set a variable to the number of items that I found on the database and then use that variable in my ng-repear limitTo

This is part of my view:

<table>
<tr ng-repeat="contact in users | limitTo:loopVar">
    <td>
        <div ng-show="!contactsElements" class="item_list">{{contact.contacts + " (" + contact.contactDesc + ")"}}</div>
    </td>
</tr>

Where loopView is the variable that I want to use

This is the Angular module/controller:

var myApp = angular.module('myApp', []);

myApp.controller('mainController', function ($scope, $http) {
$http.get('/Home/GetUser')
    .success(function (result) {
        $scope.users = result;
    })
    .error(function (data) {
        console.log(data);
    });

\\HOW I CAN SET THE loopVar HERE SO I CAN USE IT IN MY VIEW??
}

The MVC controller is below:

public JsonResult GetUser()
    {
        User userData = (User)Session["user"];            
        var db = new testDBEntities();
        return this.Json((from userObj in db.Users
                          join uc in db.UserContacts
                          on userObj.Id equals uc.usrID
                          join us in db.Users
                          on userObj.usrSupervisor equals us.Id
                          where userObj.Id.Equals(userData.Id)
                          select new
                          {
                              Id = userObj.Id,
                              usrNme = userObj.usrNme,
                              fName = userObj.usrFirstName,
                              lName = userObj.usrLastName,
                              ssno = userObj.usrSSN,
                              contacts = uc.usrContact,
                              contactDesc = uc.usrContactDescription,
                          })
                          , JsonRequestBehavior.AllowGet
                        );
    }

I hope you understand my point... In general, how I can read the returned JSON object in my Angular controller before using it in my view? As you can see, I am able to read data in my view by using ng-repeat directive but I don't know how to ready individual field in my Angular controller.

Thank you

5
  • where is loopVar defined? it doesn't appear to be a property of the users array coming from the server.... Commented Jun 15, 2016 at 19:52
  • I don't have it yet, I want to know how I can read some database object from the returned JSON in the Angular controller and then assign that value to $scope.looVar Commented Jun 15, 2016 at 19:56
  • you would assign it inside the .success callback, the same way you assigned $scope.users. If you try to assign it outside the .success, the value won't exist yet because the response hasn't been returned by the server yet (async). you may want to read up on async if you are unsure. also, it is worth noting, .success is deprecated, and it is recommended that you use .then instead. Commented Jun 15, 2016 at 20:23
  • Thank you very much for your comment. Okay, if you see my code, I am assigning the whole object to $scope.users=result in the .success. And it is working properly... What if I want to read a specific peace of data? Such as the username $scope.username=result.usrNme... This is what I am looking to do with no luck so far. Commented Jun 15, 2016 at 20:40
  • if result is a single object, then that should work correctly, assuming that it is inside the .success.... Commented Jun 15, 2016 at 20:47

1 Answer 1

1

The data object returned is formated the way you specified it in your controllers JsonResult.

To get each in the array passed from your controllers GetUser function

$http.get('/Home/GetUser')
    .success(function (result) {
        $scope.users = result;

        //Loop the json
        if (result != null) {
            for (var i = 0; i < result.length; i++) {

                //Then you get the values like this

                //result[i].Id; 
                //result[i].usrNme; 
                //result[i].fName; 
                //result[i].lName; 
                //result[i].ssno; 
                //result[i].contacts; 
                //result[i].contactDesc; 

                }
        }

    })
    .error(function (data) {
        console.log(data);
    });

If you just want to send one value from the controller into a JsonResult you can do it like this

Let's say you have a method call GetLoopVar() in your controller:

public JsonResult GetLoopVar()
{
    string loopVar = "Im a var";
    return Json(loopVar, JsonRequestBehavior.AllowGet)
}

And in your client

$http.get('/Home/GetLoopVar')
    .success(function (result) {

        $scope.loopVar = result;

        //$scope.loopVar = "Im a var"

    })
    .error(function (data) {
        console.log(data);
    }); 

To combine the two and achieve the objective here I would first make sure that the scope value is set that is used in the filter. After the loopVar is set then get the users. One way to do that is by calling the getUsers function after you have set the loopVar value like this

myApp.controller('mainController', function ($scope, $http) {

    $scope.getLoopVar = function(){
        $http.get('/Home/GetLoopVar')
            .success(function (result) {
                $scope.loopVar = result;

                //Call get user function
                $scope.getUsers();
            })
            .error(function (data) {
                console.log(data);
            });
    };

    $scope.getUsers = function(){
        $http.get('/Home/GetUser')
            .success(function (result) {
                $scope.users = result;
            })
            .error(function (data) {
                console.log(data);
            });
    };

    //To get the values on load, call the $scope.getLoopVar() in the controller
    $scope.getLoopVar();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, this was very helpful
Great! Happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.