angularjs - AngularJS 模板中的 Grails Assets 图像

标签 angularjs grails asset-pipeline

我正在使用 Grails 2.4.4 和 AngularJS 1.3.15 创建一个简单的应用程序。为了使模板与 Grails 一起使用,我使用了 AngularJS Template Asset-Pipeline Plugin 2.0.7。

我的第一个原型(prototype)没有使用 ngRoute 的任何路由逻辑。现在我想提取部分不断增长的应用程序并将它们放在单独的模板中。这几乎奏效了,但我的图像有问题。以前我使用这样的结构来加载图像作为 Assets :

<img src="${assetPath(src: 'image.png')}">

这确实有效,因为整个应用程序是一个 .gsp 页面。将代码提取到模板中不再进行此处理,并且无法再加载图像。

我目前的解决方法是:
<img src="../assets/image.png">

显然,这种技术有一些缺点。使用相对路径对 Assets 位置进行硬编码可能非常脆弱。我是否错过了一些可以帮助我将 AngularJS 与 Asset Pipeline 合并的不错的功能或命令?

最佳答案

我通过在我的 Angularjs 项目中添加一个“AssetService”来“解决”这个问题。

angular.module('myApp.assets')
.service('AssetService', [ function () {

    this.getAssetDir = function() {
        return window.grailsSupport.assetsRoot;
    };

    this.getRootDir = function() {
        return window.grailsSupport.root;
    };
}]);

这需要您的 Grails 布局文件中的一些代码......
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title><g:layoutTitle default="MyApp"/></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="${assetPath(src: 'favicon.ico')}" type="image/x-icon">
    <link rel="apple-touch-icon" href="${assetPath(src: 'apple-touch-icon.png')}">
    <link rel="apple-touch-icon" sizes="114x114" href="${assetPath(src: 'apple-touch-icon-retina.png')}">

    <!-- add this to your layout -->
    <g:javascript>
        window.grailsSupport = { 
            assetsRoot : '${ raw(asset.assetPath(src: '')) }',
            root : '${createLink(uri: '/')}' 
        };
    </g:javascript>

    <asset:stylesheet src="application.css"/>
    <asset:javascript src="application.js"/>
    <g:layoutHead/>
</head>

我在另一个堆栈溢出的答案中得到了 window.grailsS​​upport 代码 question .

您现在可以使用 AssetService 在您的 Controller 中为您的 URL 添加前缀...
angular.module('MyApp.profile')
.controller('MyCtrl', [ 'AssetService', '$http', function(AssetService, $http) {

    var self = this;
    self.pathToAnonProfile = AssetService.getAssetDir() + "ppt_Anonymous.jpg";

    $http.get(AssetService.getRootDir() + 'api/v1/users').then(function(response)    {
    ....
    }, function(errResponse) {
    ....
    }); 
}]);

它很可能会得到改进,您仍然需要混合 gsp 和纯 Angular 模板,但它将 Assets 路径保留在一个可以轻松修改的服务中。

关于angularjs - AngularJS 模板中的 Grails Assets 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29332486/

相关文章:

grails - 使用Grails在 Elasticsearch 中安装head插件

grails - 有没有办法在Grails中做到这一点?

html - Rails - 如何确保我的样式优先于 Bootstrap?

javascript - AngularJS配合ng-map实现动态热图可视化

javascript - 使用AngularJS将多维数组转为多级列表

variables - AngularJS:从 Controller 内读取路由参数

java - 如何解决原因:java.lang.ClassNotFoundException:grails.mongodb.MongoEntity

ruby-on-rails-3 - 服务 Assets 发展非常缓慢

ruby-on-rails - 为什么我的所有 sass 文件中都需要 '@import compass' 进行预编译?

c# - 从 json 中删除 xml 标签