使用AngularJS的动态元图像

时间:2015-11-09 02:53:07

标签: javascript angularjs

我在单页角应用中绑定当前所选图像的当前值时无法填充标记src属性。

以下是我到目前为止,使用标题标签上的ng-bind工作正常。

的index.html

<title ng-bind="$state.$current.locals.globals.pageTitle"></title>

即使它有点笨拙,但上面的标题仍然很好。

问题在于index.html中的这一行,我无法将previewImage值正确绑定到链接rel&#39; src&#39;属性。

  <link rel="image_src"  ng-attr-src="$state.$current.locals.globals.previewImage" />

App.js

  run.$inject = ['$http', '$rootScope','$state', '$stateParams'];

  function run($http, $rootScope, $state, $stateParams) {
    $http.defaults.xsrfHeaderName = 'X-CSRFToken';
    $http.defaults.xsrfCookieName = 'csrftoken';
    $rootScope.currentboard_id = 0;
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    $rootScope.previewImage = $state.$current.locals.globals.previewImage;
  }

路由器

 $stateProvider.state('modal', {
  url: '/post/:post_id',
  template: '<div ui-view="modal"></div>',
  resolve: {
    post: ['Posts', '$stateParams', function(Posts, $stateParams) {
      // Use Posts service to retrieve a title
      return Posts.get_post($stateParams.post_id);
  }],
    // Dynamic title showing the name of post
    pageTitle: ['post','$stateParams', function(post,$stateParams) {
      return post.data['0'].description;
  }],
     // Dynamic title showing the name of post
    previewImage: ['post','$stateParams', function(post,$stateParams) {
      // hack to get image urls from image tags
      var m,
      urls = [], 
      str = post.data['0'].image,
      rex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;

      while ( m = rex.exec( str ) ) {
        urls.push( m[1] );
      }

      return urls; 
  }]
  },
  onEnter: showModal
})

1 个答案:

答案 0 :(得分:0)

  {%verbatim%}
  <meta property="og:title" ng-attr-content="{{ $state.$current.locals.globals.pageTitle }}"/>
  <meta property="og:image" ng-attr-content="{{ $state.$current.locals.globals.previewImage }}" />
  <link rel="image_src" href="{{ $state.$current.locals.globals.previewImage }}" />
  {%endverbatim%}