Reputation: 35
I was trying to run a simple Angular example using a controller. However, it doesn't seem to work.
Here is the HTML:
<!DOCTYPE html>
<html ng-app = "app">
<head>
<title></title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/my.js"/>
</head>
<body>
<label for = "fname">Name:</label><input type="text" id="fname" ng-model="name"/>{{name}}
<div class="container" ng-controller="SimpleController">
<ul>
<li ng-repeat="hero in heroes">{{hero.name}} - {{hero.city}}</li>
</ul>
</div>
</body>
</html>
The Script my.js is :
angular.module("app",[]).controller('SimpleController',[function ($scope){
$scope.heroes =
[
{name:"Bruce Wayne", city:"Gotham"},
{name:"Kal-El", city:"Metropolis"},
{name:"Barry Allen", city:"Central City"},
{name:"Kara Jor-El", city:"National City"},
{name:"Shazam", cuty:"Fawcett City"}
];
}]);
On my local system, the ng-model directive works. But the controller doesn't. I'm using 1.4.x (stable) Angular js.
I tried other question posted and did what the answers suggest, still no result. So what am I doing wrong here?
Created a fiddle as well. Though in the fiddle, even ng-model isn't working.
Upvotes: 0
Views: 97
Reputation: 26176
if you are using modern version of AngularJS I would suggest to use ControllerAs syntax:
<div class="container" ng-controller="SimpleController as simpleController">
<ul>
<li ng-repeat="hero in simpleController.heroes">{{hero.name}} - {{hero.city}}</li>
</ul>
</div>
and in JS:
angular.module("app",[]).controller('SimpleController',function (){
this.heroes = [
{name:"Bruce Wayne", city:"Gotham"},
{name:"Kal-El", city:"Metropolis"},
{name:"Barry Allen", city:"Central City"},
{name:"Kara Jor-El", city:"National City"},
{name:"Shazam", cuty:"Fawcett City"}
];
}]);
Upvotes: 3
Reputation: 1918
You haven't injected $scope properly into your controller. You have to put '$scope' in the array. Try this :
angular.module("app",[]).controller('SimpleController',['$scope', function ($scope){
// Your Stuff
}]);
ADDED COMMENT
While its perfectly okay to pass the controller function as the second argument like the other answers in the thread, I would recommend this method (where we are passing an array with dependencies and controller function) if you want to minify your code during production.
Minifiers will frequently change variable names during minification process, this method makes sure that your dependencies will still work after that.
Upvotes: 4
Reputation: 1246
your controller should be like:
angular.module("app",[]).controller('SimpleController',function ($scope){
$scope.heroes = [
{name:"Bruce Wayne", city:"Gotham"},
{name:"Kal-El", city:"Metropolis"},
{name:"Barry Allen", city:"Central City"},
{name:"Kara Jor-El", city:"National City"},
{name:"Shazam", cuty:"Fawcett City"}
];
});
Upvotes: 1