Reputation: 225
I am working on learning the mean stack and am getting tripped up with Angular and routing. I have a javascript file, listed below that contains the routing code in the app.config module.
var app = angular.module('doorSensorReadings', ['ui.router']);
app.factory('readings', ['$http', function($http){
var o = {
readings: []
};
o.getAll = function() {
alert("test");
};
}])
app.controller('MainCtrl', ['$scope', 'readings', function($scope, readings){
$scope.readings = readings.readings;
$scope.addReading = function(){
$scope.readings.push({id: 2, name:"Door 4", open: true})
}
}]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
resolve: {
Promise: ['readings', function(readings){
return readings.getAll();
}]
}
});
$urlRouterProvider.otherwise('home');
}]);
When the page loads I would expect it to fire the code in the app.factory and send an alert box that says test. I can not figure out why the code is not being called and I am not getting any errors when I load the page. Right now it just simply loads a blank page. The "ejs" file is listed below:
<html>
<head>
<title>My Angular App!</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="javascripts/angularApp.js"></script>
</head>
<body ng-app="doorSensorReadings">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Door Sensor</h1>
<div ng-repeat="reading in readings">
{{reading.id}}, {{reading.name}}, {{reading.open}}
</div>
<button ng-click="addReading()">Post</button>
</div>
</script>
</body>
</html>
Any suggestions as to why the alert is not being fired when the page is loaded would be greatly appreciated.
Upvotes: 1
Views: 115
Reputation: 136144
You should return o
from factory
, as factory return a object.
app.factory('readings', ['$http', function($http){
var o = {
readings: []
};
o.getAll = function() {
alert("test");
};
return o;
}])
Upvotes: 1