0

I'm using GET to load some user profile data, like so -

MainController.js

   $http({
        method: 'GET',
        url: config.serverUrl + '/profile'
    }).then(function successCallback(response) {
        $scope.userdata = response.data.message.user;
    }, function errorCallback(response) {
         toastr.error('Something is wrong.');
    });

Server response

{
    "success": true,
    "message": {
        "user": {
            "id": 36,
            "email": "[email protected]",
            "name": "Rusty Rittenhouse"
        }
    }
}

Now, I'm using the following expression to show the user's name:

{{ userdata.name }} -> inputs "Rusty Rittenhouse"

How can I display only "Rusty"? Usually I would use split, but since I'm new to angular I don't know what's the best and most neat solution for this.

1 Answer 1

1

You can write a custom filter to do this:

angular.module('myApp', []).filter('firstName', function() {
    return function(input) {
        return input.split(' ')[0];
    };
});

and use it like so:

{{ userdata.name | firstName }}

or even better:

<div/span ng-bind="userdata.name | firstName"></div/span>
Sign up to request clarification or add additional context in comments.

8 Comments

wow, thanks, its pretty neat. would you say it is right to use a filter in this case?
Yes, as long as you don't want to actually modify the original data and it's not a heavy function using a filter is fine, just remember that a filter can run hundreds of times so keep it light
Could it be that either userdata or userdata.name is undefined ?
You could always add: return input ? input.split(' ')[0] : ' ';
It tries to fire the filter before your data is loaded, if you add the code from my last comment you shouldn't have the error anymore
|

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.