Angularjs list not refreshing on form submit using MEAN - angularjs

Some what new to the MEAN stack. Currently I'm reworking an small app I did through codeschool to be full MEAN stack.
The app created can be seen here
Code School app
In rewriting the app using the MEAN stack after submitting the form I must refresh the page to see the city added to the list. What do I need to fix so I don't need to refresh the page for the new Item to be added to the list?
If I'm missing any relevant code below here is my git hub link
git hub link
Here is my code:
angular.module('Cityapp').controller('CityIndexController', function(City, $scope){
$scope.cities = City.query();
window.sc = $scope;
});
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
console.log($scope.city);
console.log(data);
console.log($scope.city);
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
<form ng-controller="CityCreateController">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="saveCity(city)"/>
</form>
<ul ng-controller="CityIndexController" class="city-list">
<li ng-repeat="city in cities">
<a href="#">
{{city.city}}</a></li>
</ul>

It should looks something like that
;(function() {
function Cities($http) {
function City() {
}
City.prototype.save = function() {
return $http.post('/api/city', this);
};
City.cities = [];
City.add = function(city) {
city.save().then(function() {
City.cities.push(city);
});
};
City.getAll = function() {
$http.get('/api/cities').then(function(response) {
City.cities = response.data.map(function(data) {
return new City(data);
});
return cities;
});
};
return City;
}
function CityCreateController(Cities) {
var mv = this;
mv.city = new Cities();
mv.saveCity = function() {
Cities.add(mv.city);
};
}
function CityIndexController($scope, Cities) {
var mv = this;
$scope.$watchCollection(function() {
return Cities.cities;
}, function(cities) {
mv.cities = cities || [];
});
Cities.getAll();
}
angular
.module('app', [])
.factory('Cities', ['$http', Cities])
.controller('CityCreateController', ['Cities', CityCreateController])
.controller('CityIndexController', ['$scope', 'Cities', CityIndexController]);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<form ng-controller="CityCreateController as mv">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="mv.city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="mv.city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="mv.saveCity()"/>
</form>
<ul ng-controller="CityIndexController as mv" class="city-list">
<li ng-repeat="city in mv.cities">
<a href="#">
{{city.city}}</a></li>
</ul>
</body>
</html>

Found a simple fix
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.cities = City.query();
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
Just added the
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
to the .success. Works like it should. Now on to my next issue.

Related

How to pass data-plugin="timepicker" value to controller in angularJS

I have code to pass date and time to controller.
Here is HTML code,
<div class="page-content" ng-app="app">
<div ng-controller="postAppoinmentCtr as ctrl" class="panel-body">
<form ng-submit="submitForm()" id="form1">
<input name="time" ng-model="time" type="text" class="form-control" ng-model="time" data-plugin="timepicker" autocomplete="off"/>
<input name="date" ng-model="date" type="text" class="form-control" data-plugin="datepicker"/>
<input..ng-model="type"...></input>
<input..ng-model="Description"...></input>
<button ...>
</form>
</div>
</div>
Here is angular js part
var app = angular.module('app', []);
app.controller('postAppoinmentCtr', function($scope, $http, $location) {
$scope.submitForm = function(){
var url = $location.absUrl() + "/addAppoinment";
alert(url);
var config = {
headers : {
'Content-Type': 'application/json;charset=utf-8;'
}
}
var data = {
type: $scope.type,
date: $scope.date,
time: $scope.time,
description: $scope.description
};
$http.post(url, data, config).then(function (response) {
$scope.postResultMessage = "Sucessful!";
}, function (response) {
$scope.postResultMessage = "Fail!";
});
$scope.type = "";
$scope.date = "";
$scope.time ="";
$scope.description ="";
}
});
When click the button type and description pass to controller. But date and time not. I can do this using
<input id="date-birth" class="form-control" type="date" ng-model="date">
this line. But I need to use data-plugin="datepicker" .
I'm new one for the angularjs and I try to many ways for solve this problem.
Please give me some answer this. Thanks in advance.

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.

Uploading Multiple files from Angular JS to SQL DB using MVC Web API

<!DOCTYPE html>
<html ng-app="messageBoardApp" class="page-header">
<head>
<title></title>
<link href="../libs/bootstrap.min.css" rel="stylesheet" />
<!--<script src="Scripts/angular-route.min.js"></script>-->
<script src="../libs/angular.min.js"></script>
<script src="../libs/angular-file-upload.min.js"></script>
<script src="../libs/console-sham.min.js"></script>
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="MessageBoardModule.js"></script>
<script src="MessageBoardController.js"></script>
<script src="MessageBoardService.js"></script>
</head>
<body ng-controller="messageBoardController" class="container">
<div>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="titleText" ng-model="message.title" class="form-control" />
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="contentText" ng-model="message.content" rows="5" cols="40" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="file">File</label>
<input type="file" nv-file-select="" uploader="uploader" multiple>
</div>
<div class="form-group">
<label for="fileList">These are your selected files</label>
<br/>
<ul>
<select name="files" ng-model="selectedFile" ng-options="option.file.name for option in uploader.queue" size="4" class="form-control"></select>
</ul>
</div>
<br/>
<div class="col-sm-offset-0 col-sm-6">
<input type="button" value="Remove File" ng-click="remove()" />
<button ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">Remove all</button>
</div>
<br/>
<br/>
<br/>
<div class="col-sm-offset-4 col-sm-6">
<button ng-click="uploader.uploadAll()">Upload All</button>
<!--<input type="submit" value="Add Message" ng-click="submitForm()"/>-->
<input type="button" value="Exit" ng-click="Close()" />
</div>
</form>
</div>
</body>
</html>
Controller:
messageBoardApp.controller('messageBoardController', ['$scope', 'FileUploader', 'MessageBoardService',
function ($scope, FileUploader, MessageBoardService) {
var uploader = $scope.uploader = new FileUploader({});
$scope.remove = function (selectedItem) {
$scope.uploader.queue.splice(uploader.queue.indexOf(selectedItem), 1);
};
//$scope.message=messageBoardService.SaveMessage();
$scope.submitForm = function () {
alert("Controller");
var message = $scope.message;
MessageBoardService.SaveMessage(message);
//MessageBoardService.SaveMessage($scope.message);
};
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function (fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function (addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function (item) {
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function (fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function (progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function (fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function (fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function (fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function () {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
// -------------------------------
}]);
Service:
messageBoardApp.factory('MessageBoardService', function () {
var SaveMessage = function (newMessage) {
alert(newMessage.content);
alert(newMessage.title);
return true;
};
return {
SaveMessage: SaveMessage
};
});
Module:
var messageBoardApp = angular.module("messageBoardApp", ['angularFileUpload']);
Am using below file-upload js from this link
https://github.com/nervgh/angular-file-upload/
I understand all the files which i have selected are in queue. Am not sure how to pass this files(more than 1) to .net mvc wep api call controller and then pass value to SQL DB.
Am stuck up with passing all the form values to service and then to wep api controller.
When you initialize your FileUploader you have to say to which url you would like to post your files. For example:
var uploader = $scope.uploader = new fileUploader({
url: window.location.protocol + "//" + window.location.host + window.location.pathname + "/api/Upload/UploadFile"
});

Array not returning in angularstrap typeahead

I'm following this plunker to create a typeahead in my project.
http://plnkr.co/edit/ZjpJxXkl0v5LhQdxcqWn?p=preview
app.js (not working with my API)
$scope.getAddress = function(viewValue) {
var params = {address: viewValue, sensor: false};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {params: params})
.then(function(res) {
console.log(res);
return res.data.results;
});
};
Index.html
<!-- Using an async data provider -->
<div class="form-group">
<label><i class="fa fa-home"></i> Address <small>(async via maps.googleapis.com)</small></label>
<input
type="text"
class="form-control"
ng-model="selectedAddress"
data-animation="am-flip-x"
ng-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)"
placeholder="Enter address"
bs-typeahead>
</div>
Inn my case i'm fetching data from a .net API. When i console log the results from the API I can see the array is returning from the API. but when i try to return it to the typeahead the data isn't displayed. however if i try to create an array of mock objects and then manually insert the data into the array aswell the results appear in the typeahead.
app.js (data is displayed)
$scope.getAddress = function(viewValue) {
var params = {address: viewValue, sensor: false};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {params: params})
.then(function(res) {
console.log(res);
[{formatted_address: "Alabama"},{formatted_address: "Arkansas"},{formatted_address: res.data.results[0]}]
return res.data.results;
});
};
why could this be happening and how would i fix it?
I can't see your full solution so it's difficult to say what did you missed but please see below for working solution.
var app = angular.module('app', ['mgcrea.ngStrap']);
app.controller('firstCtrl', function($scope, $http) {
$scope.getAddress = function(viewValue) {
var params = {
address: viewValue,
sensor: false
};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: params
})
.then(function(res) {
return res.data.results;
});
};
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="//mgcrea.github.io/angular-strap/dist/angular-strap.js" data-semver="v2.1.3"></script>
<script src="//mgcrea.github.io/angular-strap/dist/angular-strap.tpl.js" data-semver="v2.1.3"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
<div class="form-group">
<label><i class="fa fa-home"></i> Address <small>(async via maps.googleapis.com)</small>
</label>
<input type="text" class="form-control" ng-model="selectedAddress" data-animation="am-flip-x" ng-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)" placeholder="Enter address" bs-typeahead>
</div>
</div>
</body>

Angular Form Post

I have the following code and when I submit the request; I get request failed. The data is not going to the server. Any idea why?
All I need is a simple form submission with the code below. I think the issue is where I'm collecting the form data using the config section. I looked around and that's how I added that. Any help will be appreciated.
Thanks.
<!-- Main Content -->
<div class="container">
<div class="page-header" ng-controller="NotesCtrl">
<h1>{{title}}</h1>
<form class="row-height" name="Form1" ng-submit="processForm('ajaxSubmitResult')">
<!--ng-submit="processForm(formData, 'ajaxSubmitResult') -->
First Name:
<input type="text" ng-model="formData.firstname" class="spacer" required/>
Last Name:
<input type="text" ng-model="formData.lastname" class="spacer" required/>
<!--<button class="btn btn-primary" ng-click="insert(formData)">Add</button>-->
<button type="submit" class="btn btn-success">Add Name</button>
</form>
<hr/>
<h4>Raw Data</h4>
{{formData}}
<hr/>
<h4>Submit Results</h4>
<span id="submitDebugText">{{ajaxSubmitResult | json}}</span>
</div>
</div>
<script>
// define angular module/app
var formApp = angular.module('formApp', []);
function NotesCtrl($scope, $http) {
$scope.title = "Test App";
$scope.formData = {};
$scope.processForm = function (resultVarName) {
var config = {
params: {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}
};
$http.post("//", null, config)
.success(function (data, status, headers, config) {
$scope[resultVarName] = data;
})
.error(function (data, status, headers, config) {
$scope[resultVarName] = "bugger! Errors.";
});
};
}
</script>
When you do something like this in the view:
<input type="text" ng-model="formData.firstname" class="spacer" required/>
In the controller, you access the property with
$scope.formData.firstName
This issue seems to be that you aren't including the formData here:
var config = {
params: {
'firstname': $scope.firstname,
'lastname': $scope.lastname
}
};
Change that to
var config = {
params: {
'firstname': $scope.formData.firstname,
'lastname': $scope.formData.lastname
}
};
And you should be good to go.

Resources