Rails Image Resources in the AngularJS Directive and Template

I have a Rails 4 application with AngularJS using these gems:

  • gem 'angularjs-rails'
  • gem 'angular -rails-templates'
  • gem 'asset_sync'

It works fine with a template like this:

    <img ng-controller='LikePostController'  
       ng-dblclick='like(post);' 
       ng-src='{{post.photo.standard}}' 
       class='lazy post_photo pt_animate_heart'
       id='post_{{post.id}}_image'
     />

The image is displayed correctly. However in my other js

petto.directive('ptAnimateHeart', ['Helper', function(Helper){
    linkFunc = function(scope, element, attributes) {
      $heartIcon = $("#heart_icon");

      if($heartIcon.length == 0) {
        $heartIcon = $("<img id='heart_icon' src='/assets/feed.icon.heart.png' alt='Like' /> ");
        $(document.body).append($heartIcon);
      }

      element.on('dblclick', function(event){
        $animateObj = $(this);
        Helper.animateHeart($animateObj);
      });
    }
    return { 
      restrict: 'C',
      link: linkFunc
    }

  }])

I got the "assets / feed.icon.heart.png" error not found from the browser console. I have feed.icon.heart.png located under app / assets / feed.icon.heart.png.

ps: Forget to mention that I use sync gem assets to place assets in amazon s3. The image worked well in development, but not in production.

+1
source share
3

, . , :

my_image.png

- ( md5-):

"my_image-231a680f23887d9dd70710ea5efd3c62.png"

:

javascript : yourjsfile.js.erb

:

$heartIcon = $("<img id='heart_icon' src='<%= image-url("feed.icon.heart.png") %>' alt='Like' /> ");

- Ruby on Rails Guides

+11

- , . app/helpers/application_helper.rb:

def list_image_assets(dir_name)
  path = File.expand_path("../../../app/assets/images/#{dir_name}", __FILE__)
  full_paths = Dir.glob "#{path}/**.*"
  assets_map = {}
  full_paths.each do |p|
    original_name = File.basename p
    asset_path    = asset_path p[p.index("#{dir_name}")..-1]
    assets_map[original_name] = asset_path
  end
  assets_map.to_json
end

, , app/assets/images, . "" .

angular ng-init ( , ):

<div ng-controller="NoController" ng-init="assets='<%=list_image_assets "images_dir_name"%>'"></div>

angular, $scope :

$scope.$watch('assets', function(value) {
  if (value) {
    $scope.assets = JSON.parse(value);
  }
});

$scope, , . ng-src, .

<img ng-src={{::assets['my_image.png']}}/>
+3

:

app.run(function($rootScope,$location){
$rootScope.auth_url = "http://localhost:3000"   
$rootScope.image_url = $rootScope.auth_url + "/uploads/user/image/"
});

dependency $rootScope

<img ng-src="{{user.image.url}}" width="100px" height="100px">

Note. It works great in the Rails API and assumes you have a custom object so that it can specify the correct image in the directory/uploads/image/

0
source

All Articles