AngularJS和Font Awesome问题

4

查看

<li ng-repeat="avatar in avatars" style="background-image: url(images/{{avatar.bg}})">
  <i>{{avatar.icon}}</i>      
</li>
<li><i>&#xf09b;</i></li>

Controller

.controller('AboutCtrl', function($scope) {
  $scope.avatars = [
    {"icon": "&#xf09b;", "bg": "github.jpeg", "href": "http://google.com"},
    {"icon": "&#xf0d4;", "bg": "twitter.jpeg", "href": "http://google.com"},
    {"icon": "&#xf081;", "bg": "gplus.jpg", "href": "http://google.com"},
    {"icon": "&#xf082;", "bg": "fb.jpg", "href": "http://google.com"}
  ];
})

问题

我在CSS文件中使用@font-face添加了“Font Awesome”字体,然后将其设置为所有<i>元素的字体。但是,当我使用Angular通过“avatar.icon”将特殊字符值插入到<i>元素时,我的字体不会呈现。

我添加了第二个<li>组以确保它确实是Angular而不是CSS特异性问题,但第二个<i>标记中的特殊字符完全正常呈现。

我知道我忽略了什么,但我想不出来。谢谢您的帮助。


顺便提一下,我还没有用这个案例进行测试(所以我不会将其发布为答案),但我曾经遇到过另一个HTML实体字符的类似问题,并通过使用JS字面字符来解决了它。即,尝试使用\uf09b而不是写入&#xf09b;。您不再需要使用ng-bind-html,只需使用常规绑定即可。 - Miral
2个回答

3

感谢您的帮助。唯一需要更正的是<i ng-bind-html='{{avatar.icon}}'></i>应该改为<i ng-bind-html='avatar.icon'></i>,在处理Angular特定属性时要去掉双括号。 - Tyler Buchea
你说得对,我打得太快了。我已经更新了答案。 - lucuma
我认为这已经更新了,所以你可以不使用ngSanitize库来完成它,只需使用ng-bind-html-unsafe(更改是附加了-unsafe)。对我来说工作得很好。 - Andrew Plummer

0

index.html

<script src="components/angular/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular-sanitize.min.js"></script>
  • !important,请确保您添加了angular-sanitize.js,否则这将无法正常工作。

app.js

angular.module('myApp', ['ngSanitize'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        redirectTo: '/home'
      })
  });

将'ngSanitize'注入到我的应用程序中。

main.js

angular.module('myApp')
  .controller('AboutCtrl', function($scope) {
    $scope.avatars = [
      {"icon": "&#xf09b;", "bg": "twitter.jpeg", "href": "http://google.com"},
      {"icon": "&#xf0d4;", "bg": "twitter.jpeg", "href": "http://google.com"},
      {"icon": "&#xf081;", "bg": "gplus.jpg", "href": "http://google.com"},
      {"icon": "&#xf082;", "bg": "fb.jpg", "href": "http://google.com"}
    ];
  });
  • 这里没有什么奇怪的,只是设置了作用域

about.html

<li ng-repeat="avatar in avatars" style="background-image: url(images/{{avatar.bg}})">
  <a class="social" href="{{avatar.href}}" target="_blank">
    <i ng-sanitize ng-bind-html="avatar.icon"></i>
  </a>
</li>
  • 使用ng-bind-html来正确处理特殊字符
  • 确保在ng-bind-html中不添加花括号

解释

以上是我的完整解决方案,包含一些相关代码以供参考。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接