angular service sample not working - angularjs

I am following a tutorial for angular and a bit stuck with service.
here is the plunk where I am stuck.
it runs into issue when injecting the parameters for consrtuctor.
Can someone please have a quick look?
plunk here
https://plnkr.co/edit/rMKt3h?p=preview
related code as follows
github.js --service code
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get('https://api.github.com/users/' + username)
.then(function(response) {
return response.data;
});
};
var getRepos = function(user) {
return $http.get(user.repos_url)
.then(function(response) {
return response.data;
});
};
return {
getUser: getUser,
getRepos:getRepos
};
};
var module = angular.module("gitHubViewer");
module.factory("github", github);
}());
index.html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="lib/script.js"></script>
<script src="github.js"></script>
</head>
<body ng-app="gitHubViewer" ng-cloak>
<div ng-controller="EmployeeController">
<div ng-show="error">{{error}}</div>
{{countDown}}
<h2>{{user.name}}</h2>
<form name="searchUser" ng-submit="search(username)">
<input type="search" required ng-model="username" />
<input type="submit" value="Search" />
</form>
{{username}}
<select ng-model="repoSortOrder">
<option value="name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="language">Language</option>
</select>
<!--<div>
<img ng-src="{{user.avatar_url}}" />
</div>-->
<table style="border:1">
<thead>
<tr>
<th>Name</th>
<th>stargazers_count</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy:repoSortOrder">
<td>
{{repo.name}}
</td>
<td>
{{repo.stargazers_count | number:2}}
</td>
<td>
{{repo.language}}
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
script.js
import angular from 'angular';
(function() {
var app = angular.module('gitHubViewer', []);
var EmployeeController = function($scope,github, $interval,$log) {
$scope.search = function(username) {
$scope.error = null;
$log.info("Searching for user : " + username);
//gitHubService.getUser(username)
// .then(onResponse, onError);
//$http.get('https://api.github.com/users/' + username)
// .then(onResponse, onError);
github.getUser(username)
.then(onResponse, onError);
if(countDownInterval!==null)
{
$interval.cancel(countDownInterval);
$scope.countDown=null;
}
};
var onResponse = function(data) {
$scope.user = data;
//$http.get($scope.user.repos_url)
// .then(onReposResponse, onError);
github.getRepos(data)
.then(onReposResponse,onError);
};
var onReposResponse = function(data) {
$scope.repos = data;
};
var onError = function(error) {
$scope.error = error;
};
var decrementCountDown = function() {
$scope.countDown -= 1;
if ($scope.countDown < 1) {
$scope.search($scope.username);
}
};
var countDownInterval = null;
var startCountDown = function() {
countDownInterval = $interval(decrementCountDown, 1000, 5);
};
$scope.username = "Angular";
$scope.message = "github viewer";
$scope.repoSortOrder = "-stargazers_count";
$scope.countDown = 5;
startCountDown();
};
app.controller("EmployeeController", ["$scope","github", "$interval","$log", EmployeeController]);
}());

It might be because of the order of the JS files listed in the HTML:
<script src="lib/script.js"></script>
<script src="github.js"></script>
Since var github is used in script.js, and it's defined in github.js, github.js should come first then script.js. Like this:
<script src="github.js"></script>
<script src="lib/script.js"></script>
I had a similar issue with Bootstrap and jQuery UI.

Related

Error: [ng:areq] Argument 'ModalController' is not a function, got undefined

I used to have all my code in one big js file, but i separated everything -- including controllers to make it modular as my little app grows (and for learning porpoises). So my ui-bootstrap modal code is in this controller and is called and worked fine. When i split the controllers into separate files i get the error below. How do i fix?
app.js
var personApp = angular.module('PersonApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
personController.js
personApp.controller('PersonController', function ($scope, $uibModal, PersonService) {
$scope.addPerson = function () {
$scope.modalModel = {
Id: 0,
firstName: '',
lastName: '',
birthDate: ''
};
$scope.$uibModalInstance = $uibModal.open({
templateUrl: '/Modal/AddEditPersonModal',
controller: 'ModalController',
scope: $scope
})
}
personModalController.js
personApp.controller('ModalController', ['$scope', function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<link href="~/Content/PageSpecific/Index.css" rel="stylesheet" />
<script src="~/Scripts/PersonApp/app.js"></script>
<script src="~/Scripts/PersonApp/filters/personFilter.js"></script>
<script src="~/Scripts/PersonApp/services/personService.js"></script>
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
<script src="~/Scripts/PageSpecific/Index.js"></script>
<div ng-app="PersonApp" class="container">
<div ng-controller="PersonController">
<div class="mb20 mt15">
<input type="text" placeholder="Search Person" ng-model="searchPerson" />
<button type="button" class="btn btn-primary pull-right mb15 mr20" data-toggle="modal" ng-model="addPersonModel" ng-click="addPerson()">Add New</button>
</div>
<table class="table header-fixed">
<thead>
<tr>
<th ng-click="sortData('Id')">
ID <div ng-class="getSortClass('Id')"></div>
</th>
<th ng-click="sortData('firstName')">
First Name <div ng-class="getSortClass('firstName')"></div>
</th>
<th ng-click="sortData('lastName')">
Last Name <div ng-class="getSortClass('lastName')"></div>
</th>
<th ng-click="sortData('birthDate')">
BirthDate <div ng-class="getSortClass('birthDate')"></div>
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in filteredPersons | orderBy: sortColumn:reverseSort | filter : searchPerson">
<td>{{person.Id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
<td>{{person.birthDate | date:"MM/dd/yyyy"}}</td>
<td>
<span class="fa fa-pencil-square-o"></span>
<span class="fa fa-remove"></span>
</td>
</tr>
</tbody>
</table>
<ul uib-pagination total-items="persons.length" ng-model="currentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" rotate="false" items-per-page="numPerPage" num-pages="numPages"></ul>
<pre>Page: {{currentPage}} / {{numPages}}</pre>
</div>
</div>
<style>
</style>
Was a simple mistake on my part. Changed the order of referenced files in the index.cshtml. personController had function trying to call modalcontroller (in personmodalcontroller)
This:
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
Became this:
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
You missed to include,$uibModalInstance
personApp.controller('ModalController', ['$scope' function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
Re define the ModalController like this. You have not injected the $uibModalInstance dependency in your controller. the $uibModalInstance inside the function parameters are only the alias reference to your dependency. You have to inject the dependency first before aliasing the dependency.
personApp.controller('ModalController', ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);

AngularJS , pushing empty element

Im quite new with angular. What am i freaky about is that following code is showing empty buttons (edit/delete) even if it looks empty (on start) :
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">
<h2>todo</h2>
<form ng-submit="todoAdd(item)">
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="submit" value="Add New">
</form>
<br>
<div ng-repeat="x in todoList">
<span ng-bind="x.todoText"></span><button id="#edit" ng-click="edit(item)">edit</button><button ng-click="remove(item)">delete</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [{}];
$scope.todoAdd = function(item) {
$scope.todoList.push({todoText:$scope.todoInput);
$scope.todoInput = "";
};
$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
//function
};
});
</script>
</body>
</html>
And also can somebody to help me after clicking on edit to push todoText to input and change caption of addnew to save? and afterthen change it to addNew again?
Thank you very much
Replace line
$scope.todoList = [{}];
to
$scope.todoList = [];
Then, it wouldn't show you empty line.
//Full code.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">
<h2>todo</h2>
<form>
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="button" value="{{actionName}}" ng-click="todoAdd()" />
</form>
<br>
<div ng-repeat="x in todoList">
<span>{{x.todoText}}</span><button id="#edit" ng-click="edit(x)">edit</button><button ng-click="remove(item)">delete</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [];
$scope.actionName = 'Add';
$scope.todoAdd = function() {
if($scope.actionName === 'Add'){
$scope.todoList.push({todoText:$scope.todoInput});
$scope.todoInput = "";
} else {
var index = $scope.todoList.indexOf($scope.temp);
console.log('index: ' + index);
$scope.todoList.splice(index, 1, {todoText:$scope.todoInput});
$scope.actionName = 'Add';
}
};
$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
$scope.todoInput=item.todoText;
$scope.temp = item;
$scope.actionName = 'Save';
};
});
</script>
</body>
</html>

Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector

This is the first time I have asked a question which I really need an answer to. I'm hoping you folks will generously share some of your answers and insights.
I've been trying to replicate the JavaScript Projects list tutorial on the angularjs.org homepage (the third tutorial from the top of the homepage) in which they have a list which you can add or delete items from, the heading for this tutorial is called 'Wire Up a Backend.'
Well, i replicated the lines of code for all of it, line for line, and it does not look like the tutorial's finished product at all. Upon closer inspection, the console logs an error about injection dependencies.
The code was the same line by line, but it still did not work.
Here is the code:
index.html:
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
projects.js:
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://ng-projects-list.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth, projectListValue) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(projectListValue);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})
.config(function($routeProvider) {
var resolveProjects = {
projects: function (Projects) {
return Projects.fetch();
}
};
$routeProvider
.when('/', {
controller:'ProjectListController as projectList',
templateUrl:'list.html',
resolve: resolveProjects
})
.when('/edit/:projectId', {
controller:'EditProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.when('/new', {
controller:'NewProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.otherwise({
redirectTo:'/'
});
})
.controller('ProjectListController', function(projects) {
var projectList = this;
projectList.projects = projects;
})
.controller('NewProjectController', function($location, projects) {
var editProject = this;
editProject.save = function() {
projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditProjectController',
function($location, $routeParams, projects) {
var editProject = this;
var projectId = $routeParams.projectId,
projectIndex;
editProject.projects = projects;
projectIndex = editProject.projects.$indexFor(projectId);
editProject.project = editProject.projects[projectIndex];
editProject.destroy = function() {
editProject.projects.$remove(editProject.project).then(function(data) {
$location.path('/');
});
};
editProject.save = function() {
editProject.projects.$save(editProject.project).then(function(data) {
$location.path('/');
});
};
});
list.html:
<input type="text" ng-model="projectList.search" class="search-query" id="projects_search"
placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projectList.projects | filter:projectList.search | orderBy:'name'">
<td><a ng-href="{{project.site}}" target="_blank">{{project.name}}</a></td>
<td>{{project.description}}</td>
<td>
<a ng-href="#/edit/{{project.$id}}"><i class="icon-pencil"></i></a>
</td>
</tr>
</tbody>
</table>
detail.html:
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">
Required {{myForm.name.$pristine}}</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="editProject.project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.site.$pristine" class="help-inline">
Required</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="editProject.project.description"></textarea>
<br>
Cancel
<button ng-click="editProject.save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">Save</button>
<button ng-click="editProject.destroy()"
ng-show="editProject.project.$id" class="btn btn-danger">Delete</button>
</form>
This is the error that shows up on the console: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=projectListValueProvider%20%3C-%20projectListValue%20%3C-%20Projects
Please help, I know there are a lot of you that are much more experienced, and I certainly hope I find some answers because I don't have much to turn to, and I've been trying to figure this out for the past couple of days now, so humbly request the help of you veteran coders, and wise sages of the stackoverflow realm.
You're attempting to inject projectListValue into your Projects service. You never actually define and inject projectListValue, and it's breaking when it attempts to get it.
--
The following gets rid of the error, by getting rid of the injection.
.service('Projects', function($q, $firebase, fbRef, fbAuth) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})

AngularJS Wire up a Backend c/p from site not working

i'm trying to get this example working in Visual Studio 2015. I've created empty project and c/p files from site and for some reason i'm getting following error:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=project&p1=Error%3A…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.3%2Fangular.min.js%3A39%3A135)
I've googled a bit around and saw similar problems with version 1.2.x, suggested fix is not working. What am i missing?
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://ng-projects-list.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth, projectListValue) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(projectListValue);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})
.config(function($routeProvider) {
var resolveProjects = {
projects: function (Projects) {
return Projects.fetch();
}
};
$routeProvider
.when('/', {
controller:'ProjectListController as projectList',
templateUrl:'list.html',
resolve: resolveProjects
})
.when('/edit/:projectId', {
controller:'EditProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.when('/new', {
controller:'NewProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.otherwise({
redirectTo:'/'
});
})
.controller('ProjectListController', function(projects) {
var projectList = this;
projectList.projects = projects;
})
.controller('NewProjectController', function($location, projects) {
var editProject = this;
editProject.save = function() {
projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditProjectController',
function($location, $routeParams, projects) {
var editProject = this;
var projectId = $routeParams.projectId,
projectIndex;
editProject.projects = projects;
projectIndex = editProject.projects.$indexFor(projectId);
editProject.project = editProject.projects[projectIndex];
editProject.destroy = function() {
editProject.projects.$remove(editProject.project).then(function(data) {
$location.path('/');
});
};
editProject.save = function() {
editProject.projects.$save(editProject.project).then(function(data) {
$location.path('/');
});
};
});
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-resource.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
list.html
<input type="text" ng-model="projectList.search" class="search-query" id="projects_search"
placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projectList.projects | filter:projectList.search | orderBy:'name'">
<td><a ng-href="{{project.site}}" target="_blank">{{project.name}}</a></td>
<td>{{project.description}}</td>
<td>
<a ng-href="#/edit/{{project.$id}}"><i class="icon-pencil"></i></a>
</td>
</tr>
</tbody>
</table>
detail.html
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">
Required {{myForm.name.$pristine}}
</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="editProject.project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.site.$pristine" class="help-inline">
Required
</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL
</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="editProject.project.description"></textarea>
<br>
Cancel
<button ng-click="editProject.save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">
Save
</button>
<button ng-click="editProject.destroy()"
ng-show="editProject.project.$id" class="btn btn-danger">
Delete
</button>
</form>
Project tree
Can anyone point me in the right direction. Thanks
You are trying to inject projectListValue service which is not defined for your module named project.

Angular (AngularFire) typeerror undefined is not a function

I have the following simple data model in Firebase:
Partners
----Name
----OrigBal
This is the HTML:
<!DOCTYPE html>
<html ng-app="bastion">
<head>
<title>Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen"/>
<link rel="stylesheet" href="css/bastion.css"/>
</head>
<body ng-controller="PartnerCtrl">
<table class="table edit">
<thead>
<tr>
<th>Name</th>
<th>Original Balance</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(id, item) in items">
<td><input type="text" ng-model="item.Name" ng-blur="updateItem(id)"/></td>
<td><input type="text" ng-model="item.OrigBal" ng-blur="updateItem(id)"/></td>
<td>
Remove
</td>
</tr>
</tbody>
</table>
<div class="well">
<h4>Add Item</h4>
<form class="form-inline" role="form" ng-submit="addItem()" novalidate>
<div class="form-group">
<input type="text" class="form-control" ng-model="newItem.Name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="newItem.OrigBal" placeholder="Original Balance">
</div>
<button type="submit" class="btn btn-default">Add</button>
</form>
</div>
<script src="/Scripts/jquery-1.9.0.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
<script src="/Scripts/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/1.0.15/firebase.js"></script>
<script src="/Scripts/angularfire.min.js"></script>
<script src="/Scripts/bastion.js"></script>
</body>
</html>
And this is the Javascript:
var app = angular.module('bastion', ['firebase']);
app.constant('FIREBASE_URI', 'https://notpublic.firebaseio.com/Partners');
app.controller('PartnerCtrl', [
'$scope', 'PartnerService', function ($scope, PartnerService) {
$scope.newItem = { Name: '', OrigBal: 0 };
$scope.currentItem = null;
$scope.items = PartnerService.getItems();
$scope.addItem = function () {
PartnerService.addItem(angular.copy($scope.newItem));
$scope.newItem = { Name: '', OrigBal: 0 };
};
$scope.updateItem = function (id) {
PartnerService.updateItem(id);
};
$scope.removeItem = function (id) {
PartnerService.removeItem(id);
};
}
]);
app.factory('PartnerService', [
'$firebase', 'FIREBASE_URI', function ($firebase, FIREBASE_URI) {
var ref = new Firebase(FIREBASE_URI);
var items = $firebase(ref);
var getItems = function () {
return items.$asObject();
};
var addItem = function (item) {
items.$add(item);
};
var updateItem = function (id) {
items.$save(id);
};
var removeItem = function (id) {
items.$remove(id);
};
return {
getItems: getItems,
addItem: addItem,
updateItem: updateItem,
removeItem: removeItem
}
}
]);
The removeItem() function works just fine, the getItems() works fine, but the addItem() and updateItem() both give the error: TypeError - undefined is not a function.
The proper values are being passed back to the PartnerService, but that is where the error occurs. I have tried rearranging the load order of the scripts, to no avail.
Is it possible that I need to include a promise with these functions in order to be sure all the data is present? I am at a bit of a loss at this point.
Thank you for any help you can give.
I see you are using functions that are not on the $firebase(ref) object, you want to use it as $firebase(ref).$asArray(), see the Angularfire api
Thanks again to #Kato. I had stopped short in coding the service and needed to actually use the function that returns all the records in order to modify the collection. Instead of this:
app.factory('PartnerService', [
'$firebase', 'FIREBASE_URI', function ($firebase, FIREBASE_URI) {
var ref = new Firebase(FIREBASE_URI);
var items = $firebase(ref);
var getItems = function () {
return items.$asObject();
};
var addItem = function (item) {
items.$add(item);
};
var updateItem = function (id) {
items.$save(id);
};
var removeItem = function (id) {
items.$remove(id);
};
return {
getItems: getItems,
addItem: addItem,
updateItem: updateItem,
removeItem: removeItem
}
}
]);
What I really needed is this:
app.factory('PartnerService', [
'$firebase', 'FIREBASE_URI', function ($firebase, FIREBASE_URI) {
var ref = new Firebase(FIREBASE_URI);
var items = $firebase(ref);
var getItems = function () {
return items.$asArray();
};
var addItem = function (item) {
getItems().$add(item);
};
var updateItem = function (id) {
getItems().$save(id);
};
var removeItem = function (id) {
getItems().$remove(id);
};
return {
getItems: getItems,
addItem: addItem,
updateItem: updateItem,
removeItem: removeItem
}
}
]);
Also thanks to #Anna Smother for noting that
return items.$asObject();
Should be
return items.$asArray();

Resources