【问题标题】:Angular not rendering <br> in my jsonAngular 未在我的 json 中呈现 <br>
【发布时间】:2014-08-10 21:00:07
【问题描述】:

我正在尝试使用 Angular 在页面上显示来自 json 的元素。它不工作。我想做的很简单。但它不起作用

这是我的代码:

http://jsfiddle.net/sqxmyrcj/1/

(function(){
    var app = angular.module('store', []);

    app.controller('PortfolioController',function(){
        this.product = gem;
    });

    var gem = 
            {
        name: 'TEmp',
        aboutme: 'A Computer Science student at <br>The University Canada.<br> <br>A Software Engineer'
        };

})();

【问题讨论】:

  • 小提琴没有显示你的代码。是故意的吗?
  • 小提琴显示断线很好
  • @KristianBarrett 这正是问题所在。我在我的网页上看不到任何内容。
  • @prajmus 我看到它是空白的。你能帮忙吗,因为我在我的网页上看不到同样的内容
  • 请立即查看。我发错链接了

标签: javascript jquery json angularjs


【解决方案1】:

所有其他 cmets / 答案都有一些有效点。您面临的主要问题是 1)您使用过时的 Angular 版本;-)和 2)您需要使用 $sce 服务来创建受信任的 HTML:

(function(app){
    app.controller('PortfolioController',function($sce){
        this.product = {
            name: 'TEmp',
            aboutme: $sce.trustAsHtml('A Computer Science student at <br>The University Canada.<br> <br>A Software Engineer')
        };
    });

})(angular.module('store', []));

http://jsfiddle.net/sqxmyrcj/7/

干杯 只园

【讨论】:

    【解决方案2】:

    有 2 种方式来管理你的控制器,你打算使用 controller as 方法,而另一种被大多数 angularians 更广泛使用的是 $scope

    docs

    基本上 $scope 被注入到控制器中并充当该容器的主要对象

    app.controller('Ctrl', function ($scope) {
      $scope.product = {
        name: ...
      };
    });
    ...
    {{product.name}}
    

    scope fiddle fix

    controller as 方法具有更大的灵活性,但也具有更多的原型复杂性。

    app.controller('Controller', function () {
      this.product = {
        name: ...
      };
    });
    
    <div ng-controller="Controller as ctrl">
       {{ctrl.product.name}}
    </div>
    

    【讨论】:

    • 当您使用控制器作为语法时嵌套视图/范围时会增加很多清晰度
    【解决方案3】:

    您的 javascript 存在一些问题。主要是你应该使用范围来设置你想在你的视图中显示的变量。请参阅此 javascript 和 html:

    JSFiddle

    HTML:

    <html ng-app="store">
    
        <body ng-controller="PortfolioController">
            <p ng-bind-html-unsafe='product.aboutme'></p>
        </body>
    
    </html>
    

    JAVASCRIPT:

    (function(){
        var app = angular.module('store', []);
    
        app.controller('PortfolioController',['$scope', function($scope){
            var gem = 
                {
            name: 'TEmp',
            aboutme: 'A Computer Science student at <br>The University Canada.<br>         <br>A Software Engineer'
            };
    
            $scope.product = gem;
    
        }]);
    })();
    

    【讨论】:

    • 那么 $scope 变量是什么?
    • @fscore $scope 是您在控制器中注入的变量。它用于使来自控制器的数据在视图中可访问。
    • 范围用于为变量分配一定的“有效范围”。每个视图/页面都有自己的范围:本地范围($scope),请参阅github.com/angular/angular.js/wiki/Understanding-Scopes
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2023-02-02
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多