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');
};
}]);
Related
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.
I have two pages-one is to create data and when I click save button text box values will be send to backend method.In another page am displaying those entered datas in table.So am using two controller methods here.
I dont know how to send text box values to backend using angular.I did it using jquery simply but I dont know angular thats why am struggling.
This is my first page to save text box details:
<div class="row ">
<label>Name<span id="required">*</span></label>
<input type="text" ng-model="item.name" class = "col-lg-5 col-md-5 col-sm-5 col-xs-10"/>
</div>
<div class="row ">
<label class="col-lg-2 col-md-2 col-sm-3 col-xs-12 ">Description</label>
<textarea ng-model="item.description"></textarea>
</div>
<div class="row marTop">
<span class="pull-right">
<button class="btn save btn-primary" ng-click="addItem(item)"><i class="fa fa-floppy-o"></i>Save</button>
<button class="btn cancel btn-default" onclick="window.location.href = '/Admin/RoleList'"><i class="fa fa-ban"></i>Cancel</button>
</span>
</div>
Script: In this method only I need to pass name and description values
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
$scope.item = {};
}
//$scope.item = aaa;
console.log(item)
//$scope.values = {
// name: 'newroleName',
// description: 'roledescription'
//};
$http.post("/Admin/RolesInsert"){
alert("success")
}
})
</script>
This is my second page to get table data( that saved name should be display in this table)
<table class="table table-hover table-bordered" id="mydata" ng-controller="myCtrl">
<thead class="colorBlue">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="">
<tr ng-repeat="x in roleList | filter:searchText">
<td>{{x.Id}}</td>
<td>{{x.name}}</td>
<td>
<i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="edit{{x.Id}}"></i>
<i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-click="update{{x.Id}}"></i>
<i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="cancel{{x.Id}}"></i>
</td>
</tr>
</tbody>
</table>
script for second table
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.values = {
};
$http.post("/Admin/getRolesList")
.then(function (response) {
$scope.roleList = response.data;
});
})
</script>
One of the ways of doing this is:
angular.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http, myFactory) {
...
function sendDataToBackend() {
var requestHeaders = {
"Content-Type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: 'your url',
headers: requestHeaders
};
httpRequest.data = $scope.items;
$http(httpRequest).then(function (response) {
//Handle the response from the server
})
}
}
Finally got an answer:
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', ["$scope","$http", function ($scope, $http ,myFactory) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
//$scope.oRoles = $scope.item
$scope.json = angular.toJson($scope.item);
console.log($scope.json)
}
$scope.myFunc = function (item) {debugger
$scope.addItem(item);
var requestHeaders = {
"Content-Type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/Admin/RolesInsert',
headers: requestHeaders
};
httpRequest.data = $scope.json;
$http(httpRequest).then(function (response) {
alert(response)
//$window.location.href = '/Admin/RoleList';
})
}
}])
</script>
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;
});
};
})
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.
I have two templates with respective controllers and service files. One template's(fleetListTemplate) controller(fleetListController) loads data from its service file(fleetService) and displays in its view(fleetListTemplate).
When this happens, and I click on one of the loaded data from fleetService, I should link fleetListController to fleetSummaryController to get data from its service file (fleetSummaryService) and display in fleetSummaryTemplate view.
Can someone please help me with the coding? Thank you.
The following are the respective modules, templates, controllers and service files.
fleetListModule
"use strict";
angular.module("fleetListModule", []);
fleetListTemplate
<div class="panel1 panel-primary">
<div class="panel-heading" align="center">TRUCKS</div>
<table class="table table-bordered table-condensed table-striped">
<tr>
<th>TruckID</th>
<th>Status</th>
<th>Dest.</th>
<th>Alerts</th>
</tr>
<tr ng-repeat="truck in trucks" ng-click="summaryData()">
<td>{{truck.truckID}}</td>
<td>{{truck.status}}</td>
<td>{{truck.destination}}</td>
<td>{{truck.alerts}}</td>
</tr>
</table>
</div>
fleetListController
"use strict";
angular.module("fleetListModule").controller("fleetListController",
['$scope', 'fleetsService',
function ($scope, fleetsService) {
$scope.trucks = fleetsService.getTrucks();
$scope.summaryData = function () {
$rootScope.$broadcast('obtainSummary');
}
}]);
fleetSummaryModule
"use strict";
angular.module("fleetSummaryModule", []);
fleetSummaryTemplate
<div class="panel2 panel-primary">
<div class="panel-heading">Summary</div>
<table class="table table-bordered table-condensed table-striped">
<tr ng-repeat="summary in truckSummary">
<td>Truck ID: {{summary.truckID}}</td>
<td>Trailer ID: {{summary.trailerID}}</td>
<td>Driver ID: {{summary.driverID}}</td>
<td>Truck Number: {{summary.truckNumber}}</td>
<td>Trailer Number: {{summary.trailerNumber}}</td>
<td>Insurance Due Date: {{summary.insuranceDueDate}}</td>
<td>Maintenance Due Date: {{summary.maintenanceDueDate}}</td>
</tr>
</table>
</div>
fleetSummaryController
"use strict";
angular.module("fleetSummaryModule").controller("fleetSummaryController",
['$scope', 'fleetSummaryService',
function ($scope, fleetSummaryService) {
$scope.$on('obtainSummary', function (event, args) {
$scope.truckSummary = fleetSummaryService.getSummary();
})
}]);
fleetSummaryService
"use strict";
angular.module("fleetSummaryModule").service("fleetSummaryService",
function () {
this.getSummary = function () {
return summary;
};
this.getSummary = function (truckID) {
for (var i = 0, len = truckSummary.length; i < len; i++) {
if (truckSummary[i].truckID === parseInt(truckID)) {
return truckSummary[i];
}
}
return {};
};
var truckSummary = [
{
truckID: 1,
trailerID: '123',
driverID: 'Alex123',
truckNumber: 'hyt 583',
trailerNumber: 'xyz213',
insuranceDueDate: '25-12-2015',
maintenanceDueDate: '31-12-2015'
},
{
truckID: 2,
trailerID: '456',
driverID: 'Alex123',
truckNumber: 'hyt 583',
trailerNumber: 'xyz213',
insuranceDueDate: '25-12-2015',
maintenanceDueDate: '31-12-2015'
},
{
truckID: 3,
trailerID: '789',
driverID: 'Alex123',
truckNumber: 'hyt 583',
trailerNumber: 'xyz213',
insuranceDueDate: '25-12-2015',
maintenanceDueDate: '31-12-2015'
}
];
});
This simple example show to you how to share data between 2 controllers "in one app"
using common service.
angular.module("app", []);
///controller1
angular.module("app").controller("controller1", function ($scope, service) {
$scope.lists = [
{ name: "maher" },
{ name: "Gaurav Ram" },
{ name: "Shaun Scovil" }
];
$scope.send = function () {
service.set("lists", $scope.lists); //set(key, value)
$scope.lists = []; //optional
}
});
///controller2
angular.module("app").controller("controller2", function ($scope, service) {
$scope.lists = [];
//get data from broadcast on the root
service.get("lists"); // get(key)
//set data
$scope.resive = function () {
if (angular.isUndefined($scope.broadcast)) {
$scope.alert = "No data to resive!";
} else {
$scope.alert = null;
$scope.lists = $scope.broadcast;
}
}
});
///service
angular.module("app").service("service", function ($rootScope) {
this.set = function (key, value) {
$rootScope.$broadcast(key, value);
}
this.get = function (key) {
$rootScope.$on(key, function (event, data) {
$rootScope.broadcast = data;
});
}
});
<!doctype html>
<html ng-app="app">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div ng-controller="controller1" class="col-md-6 col-sm-6 col-xs-6">
<div class="page-header">
<h1>controller 1</h1>
</div>
<button ng-click="send()" class="btn btn-primary">Send</button>
<div class="clearfix"></div>
<br/>
<div class="alert alert-info" ng-if="lists.length == 0">Data <b>sent</b> to controller 2, click Resive button to get data</div>
<ul class="list-group">
<li ng-repeat="list in lists" class="list-group-item" ng-bind="list.name"></li>
</ul>
</div>
<div ng-controller="controller2" class="col-md-6 col-sm-6 col-xs-6">
<div class="page-header">
<h1>controller 2</h1>
</div>
<button ng-click="resive()" class="btn btn-success">Resive</button>
<div class="clearfix"></div>
<br />
<div class="alert alert-info" ng-bind="alert" ng-if="alert"></div>
<ul class="list-group">
<li ng-repeat="list in lists" class="list-group-item" ng-bind="list.name"></li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</body>
</html>