Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually bootstrapping AngularJS and then getting the module

Tags:

angularjs

Generally, I'd do the following and there would be an ng-app in my HTML:

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

myApp.controller("AttributeCtrl", function ($scope) {
    $scope.master = {
        name: "some name"
    };
});

However, I need to manually bootstrap angular because I'm only using it in a part of my app that is loaded via jQuery's $.load(). If I do the following:

main.js - this is where the page I want to use angular on is being pulled in

$("#form").load(contextPath + url, params, function() {
    angular.bootstrap($("#angularApp"));
});

And then the page being pulled in has it's own javascript:

function AttributeCtrl($scope) {
  $scope.master = { name: "some name"};
}

This works, however, ideally, I'd like my controllers to be scoped at the module level. So I modified the above code like so

main.js

$("#form").load(contextPath + url, params, function() {
    angular.bootstrap($("#angularApp", ["myApp"]));
});

and then...

var app = angular.module("myApp"); // retrieve a module

app.controller("AttributeCtrl", function($scope) {
  $scope.master = { name: "some name"};
});

Retrieving the module this way doesn't seem to work, though. Am I doing something wrong?

like image 847
Gregg Avatar asked May 14 '13 13:05

Gregg


1 Answers

You cannot create a controller after you've bootstrapped the app. See the documentation for angular.bootstrap.

You should call angular.bootstrap() after you've loaded or defined your modules. You cannot add controllers, services, directives, etc after an application bootstraps.

like image 83
flup Avatar answered Nov 15 '22 21:11

flup