Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WARNING: Tried to load angular more than once...because of jQuery...why?

I'm trying to understand what's going on here. The warning is self explanatory, and I realize that in the app, with the code and structure I have below, it runs the ng-view twice ('test' will be logged twice in the console, so of course angular is loaded twice!)....but why?

I've read every post I could find about it, and it seems to boil down to jQuery being loaded before angular.

If I leave out jQuery or if I load jQuery after angualr (which isn't good practice from what I understand), no problem. I'd like to have jQuery to support some functionality (specifically ui-sortable). And, although it doesn't seem to be actually causing any problems, I'd like to not have it running my ng-view twice.

Am I doing something structurally wrong, or am I missing an obvious way to fix this?

Update: Plunker of the issue (check the console)

index.html:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Site Title</title>

</head>

<body ng-view>
<script type="text/javascript">
    console.log('test')
</script>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
    <script type="text/javascript" src="app_simple.js"></script>
</body>
</html>

app_simple.js:

'use strict';

/**
 * Configure client module
 */
var myApp = angular.module('myApp', 
    [
      'ngRoute'
    ]);

myApp.config(function ($routeProvider) {
  $routeProvider
    .when('/simple', {
      templateUrl: 'components/simple/simple.html',
      controller: 'SimpleCtrl'
    })
    .otherwise({
        redirectTo: '/x'
    })
});

myApp.controller('SimpleCtrl', ['$scope', '$log', '$http', function($scope, $log, $http){

}]);

simple.html: My simple content

like image 861
Ben Avatar asked Nov 20 '14 21:11

Ben


1 Answers

Ok, to summarize the help from the comments:

If jQuery is included, any <script> tags included WITHIN an ng-view will be evaluated twice. (Thanks @lossleader!).

My incorrect assumption in testing was that it was processing the entire template content twice when I tried moving the ng-view off the body onto a <div> because I saw the log message twice. It wasn't!

<body>
<div ng-view>
<script>console.log('duplicated if jQuery');</script>
</div>
</body>

So @Tom and @Wawy both had correct solutions. Either move the ng-view into a <div> or move the <script> tags into the <head> (outside of the ng-view).

like image 116
Ben Avatar answered Oct 20 '22 21:10

Ben