Reputation: 45
I have a html page that needs to render dynamic content through AngularJS. I am loading the html page using requireJS. I have included angularJS in my script tag, but unable to create the controller. I can create an angular module but cannot access the controller function below
var model = {
items: [{ id: "id1", comment: "comment1" },
{ id: "id2", comment: "comment2" },
{ id: "id3", comment: "comment3" },
{ id: "id4", comment: "comment4" }]
};
var kmapp = angular.module("kmapp", []);
kmapp.controller('FieldCodesCtrl', ['$scope', function($scope) {
alert("in con");
$scope.greeting = 'Hiiiii!';
alert($scope.greeting);
}])
I cannot read the two alerts inside my controller function.
I am very new to AngularJS. Can someone please help out?
Upvotes: 1
Views: 135
Reputation: 45
Thank you so much for the help. I used another approach. I used angular.bootstrap(document.getElementById("my_html"), ["kmapp"]);
my_html is the id of my div element This line is as good as creating ng-app I believe. It worked!
Upvotes: 1
Reputation: 9616
Make sure your module kmapp is available upfront or else you need to make provision to lazy load your modules.
Follow the following paths on ideas as to how to add a module after the bootstraping process.
http://blog.getelementsbyidea.com/load-a-module-on-demand-with-angularjs/ http://www.bennadel.com/blog/2553-loading-angularjs-components-after-your-application-has-been-bootstrapped.htm
Make sure your JS loads first and then the HTML. This is because as Angular compile sthe html it can inject proper objects/singletons from the module as it binds.
I would advise you against bundling html with requireJS. Use templates as stated by @Unome
Side points: AngularJS's module system typically does not need lazy loading unless you are dealing with a huge
Upvotes: 1
Reputation: 6900
When you create controllers, you need to attach them to an html template.
To do this you need a route provider.
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/fieldcodes', {
templateUrl: 'views/FieldCodes.html',
controller: 'FieldCodesCtrl'
})
.otherwise({
redirectTo: '/'
});
});
In the route provider you'll connect views to the corresponding controllers.
You can manually provide access to a controller using ng-controller="FieldCodesCtrl", but this will need to be explicitly placed in the template.
Upvotes: 0