2014-06-25 73 views
0

我很難重新編譯在通過ng-bind-html-unsafe插入到DOM之後在我的$ scope.content對象中找到的Angular代碼。任何人都知道如何讓Angular消化這段代碼? 感謝提前一噸!如何在消毒的HTML字符串中消化我的Angular指令? | AngularJS

PLUNKER HERE

###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'} 
    }; 
}); 

回答

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,告訴角適用於自定義HTML範圍,但是這是一個醜陋的做法。完美

<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); 
     }); 
    } 
    }; 
}); 

WORKING PLUNKER

+0

作品:

如果你想動態決定顯示的電話,您可以在$scope.contents陣列由專人傳遞到指令,$compile並追加元素這樣的。萬分感謝! – Iammesol