Angular JS控制器之间的共享功能

时间:2015-04-08 14:41:54

标签: angularjs angularjs-controller

我有这个代码: http://jsbin.com/gazajunacu/1/edit?html,js,output

       angular.module('app', [])
        .service('greeting', function Greeting() {
          var greeting = this;
          greeting.message = '<strong>Default 2</strong>';
        })
        .controller('FirstCtrl', function ($sce, greeting) {
          var first = this;

          first.greeting = $sce.trustAsHtml(greeting);  
        })
        .controller('SecondCtrl', function (greeting) {
          var second = this;

          second.greeting = greeting;  
        })

我无法让它为第一个控制器吐出html。我无法让它发挥作用。请检查脚本中缺少的内容。

感谢。

2 个答案:

答案 0 :(得分:2)

问题是你没有在你的图书馆中包含angular-sanitize.js。

实现这一目标的正确方法是:http://jsbin.com/rowukowuba/1/edit

在页面中包含angular-sanitize.js,并在html页面中使用ng-bind-html指令。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular-sanitize.js"></script>

<div>
  <span ng-bind-html="greeting"> </span> World
</div>
<div ng-controller="SecondCtrl as second">
  <span ng-bind-html="greeting.message"> </span> in Second
</div>
</body>

在javascript中,只需将html代码放在范围内,并确保包含ngSanitize(我调整了您的代码):

angular.module('app', ['ngSanitize'])
  .service('greeting', function Greeting() {
    var greeting = this;
    greeting.message = '<strong>Default 2</strong>';
  })
  .controller('FirstCtrl', function ($scope, greeting) {
  $scope.greeting = '<strong>Default 2</strong>';
  })
  .controller('SecondCtrl', function ($scope, greeting) {

    $scope.greeting = greeting;  
  });

答案 1 :(得分:1)

这应该有帮助

angular.module('app', [])
.service('greeting', function Greeting() {
    var greeting = this;
    greeting.message = '<strong>Default 2</strong>';
})
.controller('FirstCtrl', function (greeting) {
    var me = this;
    me.greeting = greeting;  
})
.controller('SecondCtrl', function ($scope,greeting) {

    var me = this;
    me.greeting = greeting;  
})

以下行创建了您的错误

first.greeting = $sce.trustAsHtml(greeting);