0

I am trying to do something that looks basic but I am not able to do it.

In have a simple directive

app.directive('mainContent', function() {
return {
    restrict: 'E',
    scope: {
        content: "="
    },
    templateUrl: 'pages/home.html'
}
})

and a main page with a simple script

<main-content content="content"></main-content>

<script type="text/javascript">
$( document ).ready(function() {
if (window.location.href.indexOf("?Admin") > -1) {
    $('.editable').attr('contenteditable','true');
}
});
</script>

The directive load the following content pages/home.html

<div class="jumbotron text-center editable">Lorem ipsum</div>

I suppose my script is unable to add contenteditable="true" attribute because the directive is creating a childscope.

How can I do this without ading my script in the pages/home.html ?

Regards

Greg
  • 473
  • 1
  • 5
  • 19

1 Answers1

1

It doesn't have to do anything with scopes really, it's just that Angular is going over the HTML once it's loaded to do its magic, and you're also doing JQuery code on document.ready as well.

So, what catches first ?

Probably JQuery is unable to find your code since Angular hasn't rendered the directive yet and the HTML isn't loaded.

I suggest 2 things:

  1. Don't use JQuery when you're using Angular.

  2. If you really must or this is just an exercise of some sort, you can wrap it in a setTimeout which makes the code wait and execute once everything is finished.

    setTimeout(function() {
        $('.editable').attr('contenteditable','true');
    }, 0);
    

Edit: You can do it in the link function of the directive, like this:

link: function (scope, element, attr) {
    $('.editable').attr('contenteditable','true');
}

Fiddle is updated.

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • Thanks for clarification. Instead of using JQuery what do you suggest to add the attribute? – Greg Apr 21 '15 at 12:10
  • 1
    @Artefact I'm sorry, I attached the wrong fiddler by mistake. It's updated now. It does work with a timeout 0 since it's not the time that matters, it's the mechanism that pushes the search till the end of the queue. You can read more about it [here](http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful) – Omri Aharon Apr 21 '15 at 13:45
  • 1
    @Artefact And regarding the attribute - it's a rule of thumb that DOM manipulations should be done in directives, so I would suggest doing that in the link function of the directive. I'm updating the fiddler to show how. – Omri Aharon Apr 21 '15 at 13:46
  • 1
    Many thanks for explanation and help. That's clear for me now! – Greg Apr 21 '15 at 14:01