angular array not outputting in ng-repeat - angularjs

I have an array called reviews in my app.js file.
I'm trying to output the two hardcoded reviews on the screen, but nothing appears.
The error in the console says that the mainfunction is undefined, but I defined it I though with the correct syntax. Can anyone tell me what's the issue with my code. currently the page is blank and no reviews are outputting to the screen.
app.js
var app = angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/page1', {
templateUrl: 'page1.html'
})
.when('/page2', {
templateUrl: 'page2.html'
});
$locationProvider.html5Mode({enabled: true, requireBase: false});
app.controller('mainController', function($scope){
$scope.reviews = [
{
name: 'Joe',
review: "awesome site. Super informative"
},
{
name: 'Bill',
review: "Sweet site dude!"
}
];
});
}]);
index.html
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<div id="headerBar">
<a ng-href="/page1" id="page1">Page 1</a>
<a ng-href="/page2" id="page2">Page 2</a>
</div>
<div id="templateView" ng-view></div>
<div id="reviews" ng-controller="mainController">
<div id="reviewOutput" ng-repeat="review in reviews">
{{review.name}}
</div>
</div>
<script src='bower_components/angular/angular.js'></script>
<script src="bower_components/angular-route/angular-route.js">
</script>
<script src="app.js"></script>
</body>
</html>
Console Error
Error: [ng:areq] Argument 'mainController' is not a function, got undefined
http://errors.angularjs.org/1.5.7/ng/areq?p0=mainController&p1=not%20a%20function%2C%20got%20undefined
at angular.js:68
at assertArg (angular.js:1885)
at assertArgFn (angular.js:1895)
at $controller (angular.js:10210)
at setupControllers (angular.js:9331)
at nodeLinkFn (angular.js:9116)
at compositeLinkFn (angular.js:8510)
at compositeLinkFn (angular.js:8513)
at compositeLinkFn (angular.js:8513)
at publicLinkFn (angular.js:8390)

Variables in angular expressions refer to attributes of the $scope. Not to local variables defined in the controller, which, by definition, are only accessible from the controller (since they are local variables).
app.controller('mainController', function($scope) {
$scope.reviews = [ ... ];
});
and
<div id="reviewOutput" ng-repeat="review in reviews">
Since you're using controllerAs, the controller itself is in the $scope, in a field that you chose to name ctrl. So the view can access the controller, and its fields. So you can do
app.controller('mainController', function() {
this.reviews = [ ... ];
});
and
<div id="reviewOutput" ng-repeat="review in ctrl.reviews">

Currently your reviews array is private. Attach it to this to make it part of the controller.
...
this.reviews = [
{
name: 'Joe',
review: "awesome site. Super informative"
},
{
name: 'Bill',
review: "Sweet site dude!"
}
];

try this https://plnkr.co/edit/1zn6FLr8oRWHE9Y89k4z?p=preview
app.controller('mainController',['$scope', function($scope){
$scope.reviews = [
{
name: 'Joe',
review: "awesome site. Super informative"
},
{
name: 'Bill',
review: "Sweet site dude!"
}];
}]);
if you want to use object in DOM you need to add $scope

Related

Routes in Angular Not working

Code
<body ng-app="ngapp">
<h2>NG App</h2>
<div>
<ng-view></ng-view>
</div>
<script src="Scripts/angular.min.js"></script>
<script>
var app = angular.module('ngapp', ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'Page1.html',
controller: 'simpCtrl'
})
.when('/view2', {
templateUrl: 'Page2.html',
controller: 'simpCtrl'
});
});
app.controller('simpCtrl', function ($scope) {
$scope.customers = [
{ name: 'Jack', age: 10 },
{ name: 'Abdul', age: 12 },
{ name: 'Zubair', age: 11 },
{ name: 'Ammar', age: 10 }
];
});
</script>
I have registered the routes properly but its is not working, I don't know why. Any Idea how to debug or find misbehaving code in angular?
Page1.html
<div>
<h2>View 1</h2>
Customer Name:
<input type="text" ng-model="search.name" />
<ul>
<li ng-repeat="n in customers | orderBy:'name' | filter:search:strict ">{{n.name|uppercase}} - {{n.age}}
</li>
</ul>
View 2
Thanks
Plunker link to code
There are few issues with your application,
(i) You are refering to angular2 library, change it like this
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.js"></script>
(ii) you have not added reference for ngRoute
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.4/angular-route.js"></script>
Working Application

Routing issue in Angular JS

i am just new to angular js and when I tried to study routing one error occurs..
please check this..
here is my index.html
<!DOCTYPE html>
<html data-ng-app="demoApp">
<head>
<title>Angular</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div data-ng-view=""> </div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
var demoApp = angular.module('demoApp', []);
demoApp.controller('firstController', function($scope) {
$scope.customers = [{
name: 'nik',
city: 'san fransisco'
}, {
name: 'henry',
city: 'new york'
}, {
name: 'avida',
city: 'california'
}, {
name: 'lynda',
city: 'texas'
}];
$scope.addCust = function($scope) {
$scope.customers.push({
name: $scope.newCust.name,
city: $scope.newCust.city
})
}
});
demoApp.config(function($routeProvider) {
$routeProvider
.when('/view1', {
controller: 'firstController',
templateUrl: '1.html'
})
.when('/view2', {
controller: 'firstController',
templateUrl: '2.html'
})
.otherwise({
redirectTo: '/view1'
});
});
</script>
</body>
</html>
routing is not working, as it supposed to load "/view2" as default when i take index.html
I hope no need to include code from 1.html and 2.html here, for reference as that just contains the 'li' tag which shows the data from this.
Error is,
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.6/$injector/modulerr?p0=demoApp&p1=Error%3A…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.6%2Fangular.min.js%3A39%3A222)
Thank.
you must include ng-route script angular-route

Angularjs Multiple modules

I am writing a website and I need two AngularJs modules: ngRoute and ui.bootstrap.
Now, my script for ngRoute is
var ngRouteApp=angular.module('ngRouteApp',["ngRoute"]);
ngRouteApp.config(['$routeProvider', function($routeProvider){
$routeProvider
... some stuff here ...
}]);
while for bootstrap is
var bootstrapApp = angular.module('bootstrapApp', ['ui.bootstrap']);
bootstrapApp.controller('CarouselCtrl', CarouselCtrl);
function CarouselCtrl($scope){
...some stuff here...
};
Now I suppose I could combine the two
angular.module("allApps", ["ngRouteApp", "bootstrapApp"]);
and into the HTML I can write
<html ng-app="allApps">
but if I do, it doesn't work. I can't see anything.
Define an angular module with all the dependences you need.
var app = angular.module('allApps',['ngRoute', 'ui.bootstrap'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
... some stuff here ...
}]);
Then use var appto define controllers.
app.controller('CarouselCtrl', [ '$scope', function ($scope){
...some stuff here...
}]);
html
<html ng-app="allApps">
user3130401 is correct, thats the proper way to do it, however, you haven't included ngRoute in your html page. Running your plunkr the console prints:
Uncaught Error: [$injector:modulerr] Failed to instantiate module allApps due to:
Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:
Error: [$injector:nomod] Module 'ngRoute' is not available!
As soon as you add the ng-route code, it works fine.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
Here is your working example.
I separated the apps as you wanted using best practices.
As you will see i'm not using the appvariable as a don't consider it best practice. Whatever you place in a javascript file outside of an iffy function is made public. That's why i prefer to use iffy functions and place all angular definitions together at the end of the file.
Also note in index.html the order i place the scripts.
<script src="ngRouteApp.js"></script>
<script src="app.js"></script>
app.js
(function(angular) {
"use strict";
function carouselDemoCtrl($scope) {
var vm = $scope;
vm.myInterval = 3000;
vm.noWrapSlides = false;
vm.activeSlide = 0;
vm.slides = [{
image: 'http://lorempixel.com/400/200/'
}, {
image: 'http://lorempixel.com/400/200/food'
}, {
image: 'http://lorempixel.com/400/200/sports'
}, {
image: 'http://lorempixel.com/400/200/people'
}];
}
carouselDemoCtrl.$inject = ["$scope"];
angular
.module("allApps", ["ngRoute", "ui.bootstrap"])
.controller("carouselDemoCtrl", carouselDemoCtrl);
})(angular);
ngRouteApp.js
(function(angular) {
"use strict";
function configs($routeProvider) {
$routeProvider
.when('/', {
template: ''
})
.when('/gallery', {
templateUrl: 'pages/gallery.html'
})
.when('/actorBio', {
templateUrl: 'pages/actorBio.html'
})
.when('/contatti', {
templateUrl: 'pages/contatti'
})
.otherwise({
redirectTo: '/'
});
}
configs.$inject = ["$routeProvider"];
angular
.module("ngRouteApp", ["ngRoute"])
})(angular);
index.html
<!doctype html>
<html ng-app="allApps">
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.1.js"></script>
<script src="ngRouteApp.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
Write your name here
<input type="text" ng-model="name"> Hi {{name}} Those are your photos:
<div ng-controller="carouselDemoCtrl" id="slides_control">
<div>
<uib-carousel active="active" interval="myInterval">
<uib-slide ng-repeat="slide in slides" index="$index">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index+1}}</h4>
</div>
</uib-slide>
</uib-carousel>
</div>
</div>
</div>
</body>
</html>

$location.path is not redirecting the document as expected

I have a very simple program where I am trying to load a page in a using a dropdown menu. But for some reason, the $location.path is not working.
Here is my code.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routing example</title>
</head>
<body ng-app="sampleApp">
<div>
<div>
<div ng-controller="RouteController">
<select ng-model="opt.selector" ng-options="opt as opt.label for opt in options">
</select>
<button ng-click="selectFn()">Go</button>
</div>
<div>
<div ng-view></div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
JS
var sampleApp = angular.module('sampleApp', []);
sampleApp .config(['$routeProvider','$locationProvider',
function($routeProvider) {
$routeProvider.
when('/one', {
templateUrl: '1.html',
//controller: 'AddOrderController'
}).
when('/two', {
templateUrl: '2.html',
//controller: 'ShowOrdersController'
}).
otherwise({
redirectTo: '/index.html'
});
}]);
sampleApp.controller('RouteController', function($scope){
$scope.options=[
{label: '1', url:'#one'},
{label: '2', url:'#two'}
];
$scope.selectFn = function($locationProvider){
$location.path($scope.opt.selector.url));
}
});
Could someone tell me where I am going wrong?
I am getting the following error:
ReferenceError: $location is not defined
at Object.$scope.selectFn
You need to inject $location into your controller so that the singleton can be used inside the controller. You are (I think trying to inject it int a function in your controller?) which won't work the way you are using it right now. If you want to do it the way you are doing right now:
sampleApp.controller('RouteController', function($scope, $location){
$scope.options=[
{label: '1', url:'#one'},
{label: '2', url:'#two'}
];
$scope.selectFn = function(){
$location.path($scope.opt.selector.url));
}
});
Although I highly recommend using the $window service to redirect

AngularJS data binding not working

I wrote some simplified code on http://jsfiddle.net/gsche/1/
When I click the "Refresh" link, the "customer.name" model doesn't update the view.
I wrote the code on my local computer and debugged it with Batarang in Chrome.
The console doesn't show any errors. The Model page in Batarang shows the customer name changing on the right, associated with an old scope id, but the id's of the $scopes also change.
Can anyone point me in the right direction?
<div ng-app>
<div ng-controller="MainCtrl">
<p> Refresh </p>
<p>
<input type="text" ng-model="customer.name">
</p>
<p>{{ customer.name }}</p>
</div>
</div>
function MainCtrl($scope) {
$scope.customer = {
name: 'TTT',
id: 0
};
$scope.Refresh = function ($scope) {
$scope.customer.name = 'Test';
};
}
Update 1 08.08.2013
Thank you all (#EpokK, #Stewie, #Hippocrates). I undestand now the problem with jsfiddle, and the example works as it should.
However, in my test application, the {{customer.name}} binding works, but the "Refresh" click still doesn't change the {{customer.name}} in the view.
Here is the content of my application. I think it is the same as the jsfiddle example:
index.html
<!doctype html>
<head>
<title>Test</title>
</head>
<body ng-app="roaMobileNgApp">
<script src="scripts/angular.js"></script>
<script src="scripts/angular-ui.js"></script>
<link rel="stylesheet" href="scripts/angular-ui.css">
<div class="container" ng-view=""></div>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
</body>
</html>
app.js
'use strict';
angular.module('roaMobileNgApp', ['ui'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
main.js
'use strict';
angular.module('roaMobileNgApp')
.controller('MainCtrl', function ($scope) {
$scope.customer = {name: '',
id: 0};
$scope.getDetails = function() {
$scope.customer.name = 'Test';
};
});
main.html
<div ng-controller="MainCtrl">
Refresh
<p><input type="text" ng-model="customer.name"> {{ customer.name }} </p>
</div>
Check my solution, I have edit your JSFiddle: http://jsfiddle.net/gsche/10/
function MainCtrl($scope) {
$scope.customer = {
name: 'TTT',
id: 0
};
$scope.getDetails = function () {
$scope.customer.name = 'Test';
};
}
Just select "No wrap - in " in fiddle options (because otherwise your demo won't work), and remove the $scope parameter from your Refresh function. You don't need to pass in $scope because the function itself is defined inside the $scope.
$scope.getDetails = function(){
$scope.customer.name = 'Test';
};
It's just the way you loaded your scripts.
I like to load angular followed by my app.js containing controllers right at the end of the body:
...
<script src="/assets/js/angular.min.js"></script>
<script src="/assets/js/app.js"></script>
</body>
To get your fiddle working, all I did was change it from "onReady" to "in body" (It's the little dropdown near the top left.)
Check this out: http://jsfiddle.net/gsche/3/
onReady means your controller definition was wrapped in an onReady function by jsfiddle. By the time angular loaded and got to work, your controller was still undefined and angular had to go ahead and spit out the raw template.

Resources