Angular Ng-show / Ng-hide Not Working Correctly With Ng-bind-html
Solution 1:
This is because the html you are injecting has not yet been compiled and linked by angular, so it is just being displayed "as is". It's being treated the same way your markup would be treated if you didn't include angular.js at all.
The solution is to create a directive that works similar to ng-bind-html, but that also includes a step for compiling and linking the html fragment.
This link is an example of such a directive.
Here is the code:
angular.module('ngHtmlCompile', []).
directive('ngHtmlCompile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$watch(attrs.ngHtmlCompile, function(newValue, oldValue) {
element.html(newValue);
$compile(element.contents())(scope);
});
}
}
});
and the usage.
<divng-html-compile="trustedHtml"></div>
And here is the working Plunk
Solution 2:
Have you injected $interpolate in the controller, and also added ngSanitize in the module?
Here's a working plnkr: http://plnkr.co/edit/qTsUzi04tCNdK5BAZvDa?p=preview
// controller.js
var app = angular.module('app');
app.controller('indexController', indexController);
function indexController($scope, $interpolate) {
$scope.my = {
messageTrue: true,
messageFalse: false
};
$scope.HtmlContent = "<divng-show='{{my.messageTrue}}'>{{my.messageTrue}}</div> ";
$scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);
}
// app.js
angular.module('app', ['ngSanitize']);
// index.html
<!DOCTYPE html><html><head></head><bodyng-app="app"ng-controller="indexController"><divng-show="my.messageTrue">{{my.messageTrue}}</div><divng-show="my.messageFalse">{{1 + 1}}</div><divng-bind-html="trustedHtml"></div><scriptdata-require="angular.js@*"data-semver="1.4.0-beta.4"src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script><scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-sanitize.js"></script><scriptsrc="app.js"></script><scriptsrc="controller.js"></script></body></html>
and this link on using ng-bind-html: How to output html through AngularJS template?
Solution 3:
$scope.my = { message: false };
$scope.HtmlContent = "<div ng-show='{{my.message}}'>{{my.message}}</div> ";
$scope.trustedHtml = $interpolate($scope.HtmlContent)($scope);
You should try this :
<divng-show="my.message == false">{{my.message}}</div><divng-bind-html="trustedHtml"></div>
Post a Comment for "Angular Ng-show / Ng-hide Not Working Correctly With Ng-bind-html"