Angular ng controller problem
Got some basic AngularJS workout but got stuck in the first place, with expressions not being evaluated using dependency ng-controller
.
index.html
<html ng-app="store">
<head>
<title>Angular JS</title>
<link rel="Stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>{{"Hello"}}</h1>
<div ng-controller="StoreController as stores">
<h1> {{stores.products.name}} </h1>
<h2> {{stores.products.price}} </h2>
<p> {{stores.products.description}} </p>
</div>
</body>
</html>
app.js
(function () {
var app = angular.module("store", []);
app.controller = ('StoreController', function () {
this.products = gem;
});
var gem =
{
name:'New Product',
price:'2.95',
description: 'This is something you would need to buy!!'
}
})();
HTML output
Hello {{stores.products.name}} {{stores.products.price}} {{stores.products.description}}
Please help me what mistake I made.
source to share
You have an = sign in your controller which is wrong.
(function () {
var app = angular.module("store", []);
////NOT app.controller = ('StoreController'.....
app.controller('StoreController', function () {
this.products = gem;
});
var gem =
{
name:'New Product',
price:'2.95',
description: 'This is something you would need to buy!!'
}
})();
source to share
This is more typical, and I would say that it is best to set any data to $scope
. Then you don't have to just use an alias for your controller and help products. You will need to enter $scope
into your controller. The code will look like this:
index.html
<html ng-app="store">
<head>
<title>Angular JS</title>
<link rel="Stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>{{"Hello"}}</h1>
<div ng-controller="StoreController">
<h1> {{products.name}} </h1>
<h2> {{products.price}} </h2>
<p> {{products.description}} </p>
</div>
</body>
</html>
app.js
(function () {
var app = angular.module("store", []);
app.controller('StoreController', ['$scope', function($scope) {
$scope.products = gem;
}]);
var gem =
{
name:'New Product',
price:'2.95',
description: 'This is something you would need to buy!!'
}
})();
source to share
Pay attention to ng-controller vs ng-repeat .
You want to set the ng-controller attribute on the controller name and in another ng-repeat attribute to repeat the data.
source to share