0

I have the following query which loops through an array of strings wikiContent. Once I show the first three values (sentences) from the array, I want to add a link that says More and when you click on it it shows the rest of the sentences.

Here is what I have (this is inside an AJAX request using $http):

var opt = "<span>";
for(var j = 0; j < wikiContent.length; j++){
    opt += wikiContent[j];
    if(j === 2){
        opt += "</span><span ng-hide='!show'>";
    }
}
opt += " ... <a href=\"\" ng-click='show=!show'>More</a>";
opt += "</span>";

$rootScope.text = opt;

When I click on More, it does 2 things:

  • It reloads the page.
  • It doesn't toggle the text

What can I do to fix both of these issues?

Here is the HTML:

<div class="panel-body" ng-bind-html="toHtml(text)"></div>

Here is the toHtml() function:

$scope.toHtml = function(string){
    return $sce.trustAsHtml(string);
};
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • 1
    You an empty href in there. You may need to add `#` or `javascript:;` or use a button. You can also stop propagation like [this](http://stackoverflow.com/questions/20300866/angularjs-ng-click-stoppropagation). – area28 Jun 22 '15 at 16:11
  • That stops the reload, but it doesn't fix the toggle of the span. – Get Off My Lawn Jun 22 '15 at 16:13
  • Is `ng-click` running? Can you alert the value of `show` in the `ng-click` to test? – area28 Jun 22 '15 at 16:16
  • Nope, it doesn't look like `ng-click` is running. No alert box displayed. I think it has something to do with dynamically adding the html... – Get Off My Lawn Jun 22 '15 at 16:17
  • Do you get any errors? [empty `href` should prevent a page reload](https://code.angularjs.org/1.4.1/docs/api/ng/directive/a) – Explosion Pills Jun 22 '15 at 16:18
  • @ExplosionPills I don't get any errors. It goes to the root page: http://nebala.com/search/google – Get Off My Lawn Jun 22 '15 at 16:20
  • 1
    With dynamic html in Angular you would need to add a `$compile` and get it into the `$scope`. [Check out this post](http://stackoverflow.com/questions/27838634/ng-click-not-working-for-dynamically-inserted-html-got-from-the-http-get-call-in) to see if it helps. – area28 Jun 22 '15 at 16:22
  • makes sense, but I am not really sure how to add that to what I have... – Get Off My Lawn Jun 22 '15 at 16:28

1 Answers1

0

After reading the documents, Angular mentioned that it is a bad idea to work with the dom from your controllers:

Note: This error often means that you are accessing DOM from your controllers, which is usually a sign of poor coding style that violates separation of concerns.

So, what I did was create an includes directory and putting included stuff in there and now I am using ng-include instead of building the dom items in the controller.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338