1

I wrote quite a simple function with some Jquery code in it and I can't get it to work for some reason.

What am I missing?

Codepen

HTML

<div ng-app='myApp'>
<div ng-controller="DropdownCtrl">

  <p>Here should be five -> &nbsp;</p>

</div>
</div>

JS

var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', function ($scope) {

  $scope.onload = function(scope) {
    $('p').each(function(){
      $(this).html($(this).html().replace(/&nbsp;/gi,"5"));
    });
  };

});
Billy Logan
  • 2,470
  • 6
  • 27
  • 45
  • if you look in your console log it tells you all your problems. 1."Uncaught ReferenceError: jQuery is not defined" 2. "Error while parsing the 'sandbox' attribute: 'allow-modals' is an invalid sandbox flag." – Josh Stevens Oct 21 '15 at 23:36
  • @JoshStevens Now, I'm done with "Uncaught ReferenceError" – Billy Logan Oct 21 '15 at 23:43

2 Answers2

2

You shouldn't be manipulating the DOM in a controller for quite a few reasons which are detailed in Angular docs and in a number of StackOverflow tickets.

Recommended Reading:

There's no load event in Angular controllers (and if there was it would be called with the $scope.$on('load',function(){}); approach).

You should be using Angular data binding / interpolation here instead. Here's an example:

<p>Here should be five -> {{number}}</p>

And your controller:

var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', function ($scope) {
  $scope.number = 5;
});
Community
  • 1
  • 1
David Boskovic
  • 1,469
  • 9
  • 14
1

A few things:

  1. The codepen has jqueryui and jquery in the wrong order, so you get an error. Also, the controller is called MainCtrl but in the HTML you have DropdownCtrl.

  2. As for the actual mistake: just because you call a function onload doesn't mean that it actually executes when the controller starts. Take it out of that function and it'll do what you intended.

Like so:

myApp.controller('MainCtrl', function ($scope) {
    $('p').each(function(){
      $(this).html($(this).html().replace(/&nbsp;/gi,"5"));
    });
});

New pen

While this might work in this instance, you shouldn't be manipulating the DOM in the controller anyways. The first rule of Angular controllers is:

"Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation."

Read More at angularjs.org →

David Boskovic
  • 1,469
  • 9
  • 14
Jorg
  • 7,219
  • 3
  • 44
  • 65
  • Life saviour. Because of your comment I learned how to set up JQuery, how to set up Angular and how to start the snippet of code when the app loads. thank you tons ;) – Billy Logan Oct 21 '15 at 23:46
  • @BillyLogan this can end up with Angular errors (they try to detect and error with you manipulating DOM in the controller). I don't recommend this approach. – David Boskovic Oct 21 '15 at 23:52