javascript - How to use HTML tags/Attributes in JSON file with Angular -
i have json file has html tags place in objects. possible use html attributes?
js
var app = angular.module('app', []); app.controller('mainctrl', function ($scope) { $scope.colors = [ { "color": "red", "value": "#f00", "message": "simple message" }, { "color": "green", "value": "#0f0", "message": "message <strong>html</strong> tags" }, { "color": "blue", "value": "#00f", "message": "am going work? should not!" }, { "color": "magenta", "value": "#f0f", "message": "<img src='https://c2.staticflickr.com/4/3684/11803460685_dd40050e8e_h.jpg'>" } ] $scope.currentmessage = ""; $scope.popupbtn = function (message) { // set current message $scope.currentmessage = message; // if popup not open, open if (!($scope.popupblcok)) { $scope.popupblock = true; } } });
css
.alert-block { background-color: coral; color: white; display: none; } .popup-container { display: block; }
html
<body ng-app="app"> <div ng-controller="mainctrl"> <ul class="block-elements"> <li ng-repeat="details in colors"> <button ng-click="popupbtn(details.message)" ng-style="{ color: details.color }">click me</button> </li> </ul> <div class="alert-block" ng-class="{'popup-container': popupblock}"> <div> <a>{{currentmessage}}</a> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script> </div> </body>
you need use $sce
along ng-bind-html
. so, should first replace:
<a>{{currentmessage}}</a>
with
<a ng-bind-html="currentmessage"></a>
and in popupbtn
scope method:
$scope.currentmessage = $sce.trustashtml(message);
the above force angular trust html snippet cross side scripting.
here go:
var app = angular.module('app', []); app.controller('mainctrl', function($scope, $sce) { $scope.colors = [{ "color": "red", "value": "#f00", "message": "simple message" }, { "color": "green", "value": "#0f0", "message": "message <strong>html</strong> tags" }, { "color": "blue", "value": "#00f", "message": "am going work? should not!" }, { "color": "magenta", "value": "#f0f", "message": "<img src='https://c2.staticflickr.com/4/3684/11803460685_dd40050e8e_h.jpg'>" }] $scope.currentmessage = ""; $scope.popupbtn = function(message) { // set current message $scope.currentmessage = $sce.trustashtml(message); // if popup not open, open if (!($scope.popupblcok)) { $scope.popupblock = true; } } });
<body ng-app="app"> <div ng-controller="mainctrl"> <ul class="block-elements"> <li ng-repeat="details in colors"> <button ng-click="popupbtn(details.message)" ng-style="{ color: details.color }">click me</button> </li> </ul> <div class="alert-block" ng-class="{'popup-container': popupblock}"> <div> <a ng-bind-html="currentmessage"></a> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script> </div> </body>
Comments
Post a Comment