0

在通过 ng-bind-html-unsafe 将 $scope.content 对象插入 DOM 后,我无法重新编译在 $scope.content 对象中找到的 Angular 代码。有人知道如何让 Angular 消化这段代码吗?提前致谢!

柱塞在这里

###index.html###
<body ng-controller="MainCtrl">
 <h2>HTML Testing</h2>
 <div ng-bind-html-unsafe="content.iPhone"></div>
</body>

###app.js###
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.content = {
    iPhone: "<div ng-style=\"style.iPhoneTest\">This shows up on an iPhone</div>",
    iPad: "<div ng-style=\"style.iPadTest\">This shows up on an iPad</div>",
    androidPhone: "<div ng-style=\"style.androidPhoneTest\">This shows up on an Android          phone</div>",
    androidTablet: "<div ng-style=\"style.androidPhoneTablet\">This shows up on an Android tablet</div>"
  };
  $scope.style = {
    iPhoneTest: {background: 'blue', color: 'black'},
    iPadTest: {background: 'black', color: 'white'},
    androidPhoneTest: {background: 'yellow', color: 'black'},
    androidTabletTest: {background: '#111', color: 'white'}
  };
});
4

1 回答 1

1

为什么不使用指令而不是注入?

<body ng-controller="MainCtrl">
 <h2>HTML Testing</h2>
 <div ng-my-phones="style"></div>
</body>

app.directive("ngMyPhones", function(){
 return {
   scope: {
    "style": "=ngMyPhones"
   },
   template: '<div ng-style=\"style.iPhoneTest\">This shows up on an iPhone</div>'+
'<div ng-style=\"style.iPadTest\">This shows up on an iPad</div>'+
'<div ng-style=\"style.androidPhoneTest\">This shows up on an Android phone</div>'+
'<div ng-style=\"style.androidPhoneTablet\">This shows up on an Android tablet</div>'
 }
});

否则,您必须使用$compile, 来告诉 Angular 在自定义 html 上应用范围,但这是一种丑陋的方法。

如果您想动态决定显示哪个电话,您可以将$scope.contents数组传递到指令中,$compile并手动添加元素,如下所示:

<body ng-controller="MainCtrl">
       <h2>HTML Testing</h2>
       <div ng-my-phone="content.iPhone" ng-my-phone-style="style"></div>
     </body>
</html>


 app.directive("ngMyPhone", function($compile){
  return {
    scope: {
      "ngMyPhone": "=",
      "style": "=ngMyPhoneStyle"
    },
    link: function($scope, $element){
       var oldPhoneElement; 

       //Everytime the phone
       $scope.$watch("ngMyPhone", function(newContent){
         angular.element(oldPhoneElement).remove();
         oldPhoneElement = angular.element(newContent);

         $compile(oldPhoneElement)($scope);
         $element.append(oldPhoneElement);
       });
    }
  };
});

工作柱塞

于 2014-06-25T06:44:26.567 回答