panzhuli
panzhuli

Reputation: 2940

Search array without ng-repeat in Angular

I'm fairly new in Angular and have an object I'm creating during the user flow. The user is basically setting some preferences, including choosing an avatar from a set of available images. I need to be able to show that avatar as associated with that individual. I need to do it by ID since these avatars will be stored in a DB for launch.

I want to set the background image of a dom element to this image.

Here's a plunkr showing what I'm trying to do. ng-repeat doesn't seem right for an inline style to me. Other options? Sample code:

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.avatars = [
                { 
                    'id': 1,
                    'image': '../images/placeholder/avatar-settings-dog.png'
                },
                { 
                    'id': 2,
                    'image': '../images/placeholder/avatar-settings-ladybug.png'
                },
                { 
                    'id': 3,
                    'image': '../images/placeholder/avatar-settings-cat.png'
                },
                { 
                    'id': 4,
                    'image': '../images/placeholder/avatar-settings-horse.png'
                }
            ];

  $scope.users = [
    { 
     'id': 0,
     'name': 'Joe',
     'avatarID': 2
    },
    {
      'id': 1,
      'name': 'Mary',
      'avatarID': 4
    }
  ]
});

and the view:

<div ng-controller="MainCtrl">
    <p ng-repeat="user in users" style="background:url(AVATAR PATH);">Hello {{user.name}}!</p>
  </div>

Upvotes: 0

Views: 378

Answers (2)

Mukund Kumar
Mukund Kumar

Reputation: 23211

use this code:

see plunker

Html code:

 <body ng-controller="MainCtrl">
        <p ng-repeat="user in users" style="background:url({{returnimageurl(user)}});">Hello {{user.name}}!</p>
      </body>

and Js code:

$scope.returnimageurl=function(user){
    for( key in $scope.avatars){
      if(user.avatarID==$scope.avatars[key].id){
        return $scope.avatars[key].image;
      } 
    }
  }

Upvotes: 1

Tom
Tom

Reputation: 7740

Use ng-style to programmatically set the style.

<p ng-repeat="user in users"
   ng-style="getAvatarBackground(user)">Hello {{user.name}}</p>

And then your controller:

$scope.getAvatarBackground = function(user) {
    var avatar = // find the correct object in $scope.avatars based on user.avatarID

    return {
      background: "url('" + avatar.image + "');"
    }
}

And an example to find the avatar object:

function findAvatarById(avatarId) {
    for(var i = 0; i < $scope.avatars.length; i++) {
        if($scope.avatars[i].id === avatarId) {
           return $scope.avatars[i]
        }
    }
}

And then

var avatar = findAvatarById(avatarId);

Upvotes: 3

Related Questions