BDillan BDillan - 5 months ago 48
AngularJS Question

ng-show not working for dynamically added HTML within my controller

Please see relevant JSFiddle

Within this code I dynamically added in sanitized HTML code using ng-bind-html but when assigning ng-show to the html it does not work. I tried using $compile but so far nothing as well.

I am trying to hide and show an element using ng-show but both are visible.


var app = angular.module('App', ['ngSanitize'])

app.controller('MyCtrl', function($scope, $compile) {

$scope.myHTML = [];

$scope.myHTML.push('<li ng-show = "visible(1)">Test1</li>');
$scope.myHTML.push('<li ng-show = "visible(0)>Test2</li>');

$scope.visible = function(arg)
if (arg == 1) return true;
if (arg == 0) return false;





<div ng-app="App">
<div ng-controller="MyCtrl">
<ul ng-repeat="snippet in myHTML" ng-bind-html="snippet"></ul>


Your controller should pretty much never be aware of markup, ever. That's the power of MVC. You should repeat across a real dataset and build up markup in your view. Something like the following, where you set items = [item1, item2] in a controller.

<div ng-app="HelloApp">
    <div ng-controller="MyCtrl">
        <ul ng-repeat="item in items">
           <li ng-show = "test($index)">Test{{$index}}</li>

If you really need to do it the way you're doing, you should use a custom directive and use angular.element to append your compiled html to the current directive element. ng-bind-html doesn't expect a compiled node, rather just an html string.