0

I'm using angular to make a $http get request for some data (I removed the URL to make it easier to read here):

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

app.controller('UserProfile', ['$http', function($http){

     var profile = this;

     profile.bio = [ ];

     $http.get('URL').success(function(data){

          profile.bio = data;

     });

}]);

Said data is always random and is organized like this:

"person": {
    "gender": "female",
    "first-name": "Yvonne",
    "family-name": "Young",
    "pictureURL": "/assets/img/female2.png"
}

I'm trying to figure out how to add specfic classes to an html element based on if the gender returns male or female. Any ideas what else I need to add to my controller for it to do this? Thanks!

Here's my failed attempt:

var app = angular.module('pointsource', []);
app.controller('UserProfile', ['$http', function($http){
var profile = this;

profile.bio = [ ];

$http.get('http://applicant.pointsource.us/api/testUser/57869704f62a2d8f3c05da99').success(function(data){
  profile.bio = data;
  if (profile.bio.person.gender == 'male') {
      $('#gender').addClass('male');
  }
});
}]);

1 Answer 1

0

If you are using jquery to make DOM changes in an angular controller it is usually an indication that you are doing it the wrong way. A better approach would be the ngClass directive (https://docs.angularjs.org/api/ng/directive/ngClass) and bind this to the value in the controller.

<div ng-controller="UserProfile as profile>
    <div id="gender" ng-class="profile.bio.person.gender"></div>
</div>

and in the controller you don't need to make any reference to the DOM element at all:

app.controller('UserProfile', ['$http', function($http){
var profile = this;

profile.bio = [ ];

    $http.get('http://applicant.pointsource.us/api/testUser/57869704f62a2d8f3c05da99'    ).success(function(data){
  profile.bio = data;

    });
}]);

Have a look at https://plnkr.co/edit/kfDtUGTHbmBtmd3BJA6j?p=preview for a simple example.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.