can not add data in sql server database in angularjs? - javascript

I Have simple app in Angularjs and I have little experience in Angularjs.
my question is I can add data in database . I think I have no errors that prevent me from adding that data.
There no errors displayed but the data not send correctly
GoverController
public ActionResult Index(Governorate gov)
{
string message = "";
if (ModelState.IsValid)
{
using (DoctorEntities dc = new Models.DoctorEntities())
{
dc.Governorates .Add(gov);
dc.SaveChanges();
message = "تم اضافة المحافظة";
}
}
else
{
message = "خطا";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
gov.js
(function () {
angular.module('MyApp', [])
.controller('AdminController', function ($scope, RegisterService) {
$scope.submitText = "save";
$scope.submitted = false;
$scope.message = '';
$scope.isFormValid = false;
$scope.gov = {
GovernorateName: ''
};
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
$scope.SaveDate = function (data) {
if (submitText == "save") {
$scope.submitted = true;
$scope.message = '';
}
if ($scope.isFormValid==false){
$scope.submitText = "please wait....";
$scope.gov = data;
RegisterService.SaveFoemData($scope.gov).then(function (d) {
alert(d);
if (d == 'success') {clearform(); }$scope.submitText='save';
} );
}
else{
$scope.message='please fill required data';
}
};
function clearform(){
$scope.gov=null;
$scope.f1.$setPristine();
$scope.submitted=false;
}})
.factory('RegisterService', function ($http,$q) {
var fac = {};
fac.SaveFoemData = function (data) {
var defer = $q.defer();
$http({
url: '/Gover/Index',
method: 'get',
data: JSON.stringify(data),
headers: {'content-type':'application/json'}
}).success(function (d) {
defer.resolve(d);
}).error(function (e) {
defer.reject(e);
});
return defer.promise();
}
return fac;
});
})();
AddGov.cshtml
#{
ViewBag.Title = "AddGov";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddGov</h2>
<div ng-controller="AdminController">
<form novalidate name="f1" ng-submit="SaveData(gov)">
{{message}}
<table>
<tr>
<td>
<input type="text" ng-model="gov.GovernorateName" name="GovernorateName" ng-class="submitted?'ng-dirty':''" required autofocus />
</td>
</tr>
<tr>
<td><input type="submit" value="{{submitText}}" /></td>
</tr>
</table>
</form>
</div>
#section scripts{
<script src="~/Scripts/MyProject/gov.js"></script>
}
i tried to find solution to this question

Related

Trying to activate a checkbox from a controller that lives in another controller

I am trying to activate a checkbox from a controller that lives in another controller. For example, I have a card named information technology under a separate controller and when I click this I want it to route to another page that has a checkbox for information technology from another controller and I want it checked as it renders the page.
The application architecture is very lengthy so I wont include any code base here. But I would like to know an approach I can take.
This is the controller where I want the logic to live and to mark a text box as checked (which lives on another controller).
angular
.controller("mycontroller", mycontroller);
mycontroller.$inject = [
"$scope"
];
// getting the getData() data
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
Below: Is the controller where the checkbox controller lives
angular
.controller('supplierIntelligenceCtrl', function ($scope, $q, FetchData, dataStore, SharedService,
$document, $window, $state, $rootScope, $timeout, DataCache,
$filter, $interval, $localStorage, $http) {
$scope.getData = function (data, type) {
console.log("whats this data about in getData(data) ", data)
$scope.query = data.name;
if (data.checked == undefined) {
data.checked = true;
}
}
$scope.apply = function (type) {
$scope.select = false;
$scope.bigres = 0;
$scope.mobFil = 3;
$scope.applyFilter(type);
}
$scope.disableApply = false;
$scope.disableApply2 = false;
$scope.applyFilter = function (type) {
console.log("this is type ", type)
if (type == 'industries') {
$scope.filters.industries = $scope.industries.filter(function (e) {
console.log("this is e ", e.checked)
return e.checked;
}).map(function (f) {
console.log(" this is f >>>> ",
f)
return f.id
})
$scope.filters.countries = [];
if ($scope.countries != undefined) {
$scope.countries = $scope.countries.map(function (e) {
e.checked = false;
return e;
})
}
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.industries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCountriesByIndustries('industries=' + $scope.filters.industries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.countries = res.data;
$scope.countriesPage += 10
}, function () {
$scope.disableApply2 = false;
});
} else {
$scope.callBackend();
}
}
if (type == 'countries') {
$scope.filters.countries = $scope.countries.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id;
})
$scope.filters.cities = [];
if ($scope.cities != undefined) {
$scope.cities = $scope.cities.map(function (e) {
e.checked = false;
return e;
})
}
$scope.start = 0;
if ($scope.filters.countries.length > 0) {
$scope.callBackend();
$scope.disableApply2 = true;
FetchData.fetchDNBCitiesByIndustriesAndCountries('industries=' + $scope.filters.industries + '&countries=' + $scope.filters.countries + '&size=').then(function (res) {
$scope.disableApply2 = false;
$scope.cities = res.data;
}, function () {
$scope.disableApply2 = false;
})
} else {
$scope.callBackend();
}
}
if (type == 'cities') {
$scope.filters.cities = $scope.cities.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.id
})
$scope.start = 0;
$scope.callBackend();
}
if (type == 'classifications') {
$scope.filters.classifications = $scope.classifications.filter(function (e) {
return e.checked;
}).map(function (f) {
return f.statusCode;
})
$scope.start = 0;
$scope.callBackend();
}
}
}
Here is the HTML where the checkbox lives:
<div ng-repeat="data in industries ">
<input id="{{data.id}}in" type="checkbox" aria-invalid="false"
ng-model="data.checked"
ng-change="getData(data,'industry')">
<label for="{{data.id}}in">{{data.name}}</label>
</div>
Maybe Im missing the point here and perhaps am overlooking something. Im new to angularjs and need to implement this capability to route a button/card to another page that checks a checkbox filter.
Please - any advise would be great . :)
Here is an example of controllers sharing an array via a shared service injected by the dependency injector. Check the checkbox in one controller and it shows in the other.
angular.module('app', []);
angular.module('app')
.factory('dataService', [function () {
return {
data: [
{ prop: '1', checked: false },
{ prop: '2', checked: false },
{ prop: '3', checked: false },
{ prop: '4', checked: false }
]
};
}]);
angular.module('app')
.controller('controller1', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller2', ['dataService', function (dataService) {
this.data = dataService.data;
}]);
angular.module('app')
.controller('controller3', ['dataService', function (dataService) {
this.toggleAll = () => {
dataService.data.forEach(item => item.checked = !item.checked)
};
}]);
[ng-controller] { display: inline-block; margin-right: 30px; vertical-align: top; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="controller1 as ctrl">
<strong>Controller 1</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller2 as ctrl">
<strong>Controller 2</strong>
<div ng-repeat="item in ctrl.data">
<label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
</div>
</div>
<div ng-controller="controller3 as ctrl">
<strong>Controller 3</strong>
<div>
<button ng-click="ctrl.toggleAll()">Toggle all</button>
</div>
</div>
</div>
Put industries as a property on a shared service that you inject into both of the controllers by the dependency injector. Then one controller can bind it to it's view and the other one can change the checked properties on them.
Since you are talking about redirection and then checking a check box, you can try either of below options
Send selection 'information technology' in query string to redirected page and check the check box
If you own a back end server then put the value in cookie and read it in your angular js app
Hope this helps.

#ModelAttribute in my REST comes empty

I am trying to pass data through <select multiple> from HTML to my RESTful.
That data is an array of String. I don't know why when it comes to my backend it's empty.
This is my REST:
#PutMapping("/events")
#Timed
public ResponseEntity<Event> updateEvent(#RequestBody Event event, #ModelAttribute("attendeesToParse") ArrayList<String> attendeesToParse) throws URISyntaxException {
//Some code
}
This is my HTML:
<div class="form-group">
<label>Attendees</label>
<select class="form-control" multiple name="attendeesToParse" ng-model="vm.usernames"
ng-options="customUser as customUser.username for customUser in vm.customusers">
<option value=""></option>
</select>
</div>
I tried to fix this one for days, I googled it so much but I found no solutions. Please help me.
I can not change my HTML into a JSP due to my project's structure and business logic.
Why does it come empty? If I try to show some logs I see an empty array [].
UPDATE
My HTML form call:
<form name="editForm" role="form" novalidate ng-submit="vm.save()">
<!-- some code -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
<span class="glyphicon glyphicon-ban-circle"></span> <span data-translate="entity.action.cancel">Cancel</span>
</button>
<button type="submit" ng-disabled="editForm.$invalid || vm.isSaving" class="btn btn-primary">
<span class="glyphicon glyphicon-save"></span> <span data-translate="entity.action.save">Save</span>
</button>
</div>
</form>
My event-dialog-controller.js: (is the .js controller that works with form)
(function() {
'use strict';
angular
.module('businessRequestApp')
.controller('EventDialogController', EventDialogController);
EventDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Event', 'Desk', 'CustomUser'];
function EventDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, entity, Event, Desk, CustomUser) {
var vm = this;
vm.event = entity;
vm.clear = clear;
vm.datePickerOpenStatus = {};
vm.openCalendar = openCalendar;
vm.save = save;
vm.reftables = Desk.query({filter: 'event-is-null'});
$q.all([vm.event.$promise, vm.reftables.$promise]).then(function() {
if (!vm.event.refTable || !vm.event.refTable.id) {
return $q.reject();
}
return Desk.get({id : vm.event.refTable.id}).$promise;
}).then(function(refTable) {
vm.reftables.push(refTable);
});
vm.customusers = CustomUser.query();
$timeout(function (){
angular.element('.form-group:eq(1)>input').focus();
});
function clear () {
$uibModalInstance.dismiss('cancel');
}
function save () {
vm.isSaving = true;
if (vm.event.id !== null) {
Event.update(vm.event, onSaveSuccess, onSaveError);
} else {
Event.save(vm.event, onSaveSuccess, onSaveError);
}
}
function onSaveSuccess (result) {
$scope.$emit('businessRequestApp:eventUpdate', result);
$uibModalInstance.close(result);
vm.isSaving = false;
}
function onSaveError () {
vm.isSaving = false;
}
vm.datePickerOpenStatus.date = false;
function openCalendar (date) {
vm.datePickerOpenStatus[date] = true;
}
}
})();
My event-service.js:
(function() {
'use strict';
angular
.module('businessRequestApp')
.factory('Event', Event);
Event.$inject = ['$resource', 'DateUtils'];
function Event ($resource, DateUtils) {
var resourceUrl = 'api/events/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.date = DateUtils.convertLocalDateFromServer(data.date);
}
return data;
}
},
'update': {
method: 'PUT',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
copy.date = DateUtils.convertLocalDateToServer(copy.date);
return angular.toJson(copy);
}
}
});
}
})();
My event.controller.js:
(function () {
'use strict';
angular
.module('businessRequestApp')
.controller('EventController', EventController);
EventController.$inject = ['Event', 'CustomUser', '$scope'];
function EventController(Event, CustomUser, $scope) {
var vm = this;
vm.events = [];
vm.customUsers = [];
vm.usernames = ["test1", "test2", "test3"];
$scope.allCustomUsers = [];
loadAll();
function loadAll() {
Event.query(function (result) {
vm.events = result;
vm.searchQuery = null;
});
CustomUser.query(function (result) {
vm.customUsers = result;
vm.searchQuery = null;
for (var i = 0; i < vm.customUsers.length; i++) {
$scope.allCustomUsers.push(vm.customUsers[i].username);
}
});
}
}
})();
If you're using angularJS, you can't data bind data with #ModelAttribute, because #ModelAttribute exists only with template engines such as JSP, and AngularJS is not a template engine within Spring. Try instead to use #RequestBody on String parameter, and then extract the data using Jackson.
One more issue, How exactly do you pass your values from front to back? I don't see any $http angularJS call, and no HTML form with POST method.

AngularJS Http Post Method not working

I am trying to do a http post into database using AngularJS. My code doesn't shows any error, but my database is not being updated and I can't figure it out why. Here is my code:
//topic-service.js
(function() {
'use strict';
angular.module('topic').factory('topicService', topicServiceFunction);
topicServiceFunction.$inject = [ '$http', '$q' ];
function topicServiceFunction($http, $q) {
var topicService = {
getTopics : getTopics
}
return topicService;
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
return $http.post('http://localhost:8080/restapp/api/topic',
JSON.stringify(obj)).then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
return deferred.reject(response.data);
}
}, function(response) {
return deferred.reject(response.data);
});
}
}
}())
//topic-controller.js
(function() {
'use strict';
angular.module('topic').controller('topicController',
topicControllerFunction);
topicControllerFunction.$inject = [ '$scope', 'topicService' ];
function topicControllerFunction($scope, topicService) {
$scope.getTopics = getTopics;
function getTopics(topicId,name,description,categId,userId) {
console.log('-->topictrlFunction');
$scope.topics = [];
var obj={
id:$scope.topicId,
name:$scope.name,
description:$scope.description,
id_category:$scope.categId,
user_id:$scope.userId
}
var promise = topicService.getTopics(obj);
promise.then(function(data) {
if (data != undefined && data != null) {
$scope.topics = data;
} else {
$scope.topics = undefined;
}
}, function(error) {
console.log('error=' + error);
$scope.topics = undefined;
})
topicService.getTopics(obj);
$scope.topics = topicService.getTopics(obj);
}
}
}())
//topic.html
<!DOCTYPE html>
<html lang="en" ng-app="myTopics">
<head>
<meta charset="UTF-8">
<script src="../../../bower_components/angular/angular.js"></script>
<script src="app.js"></script>
<script src="topics/module/topic-module.js"></script>
<script src="topics/controller/topic-controller.js"></script>
<script src="topics/service/topic-service.js"></script>
<title>Topics</title>
</head>
<body>
<div ng-controller="topicController">
<div ng-controller="topicController">
<p>
Topic id: <input type="text" ng-model="topicId">
</p>
<p>
Name: <input type="text" ng-model="name">
</p>
<p>
Description: <input type="text" ng-model="description">
</p>
<p>
Id category: <input type="text" ng-model="categId">
</p>
<p>
User id: <input type="text" ng-model="userId">
</p>
<button ng-click="getTopics(topicId,name,description,categId,userId)">Add
topic</button>
<ul ng-repeat="topic in topics">
<li>{{topic.id}} --{{topic.name}} -- {{topic.description}} --
{{topic.id_category}}--{{topic.user_id}}</li>
</ul>
</div>
</body>
</html>
In your service you use $q but return $http promise, that's counter productive, just return deferred promise:
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
var data = JSON.stringify(obj)
$http.post('http://localhost:8080/restapp/api/topic', data)
.then(function(response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
}
If it still doesn't work you should try to send urlencoded data and not json :
for this just add this header in your request : headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
and encode data with $httpParamSerializerJQLike service. (Inject it in your service)
function getTopics(obj) {
console.log('-->topicServiceFunction');
console.log(obj.name);
var deferred = $q.defer();
var data = $httpParamSerializerJQLike(obj);
var config = {
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
};
$http.post('http://localhost:8080/restapp/api/topic', data, config)
.then(function(response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
})
.catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
}

Laravel and Angular js file upload

How I can save images with laravel and angular js ?
are more inputs , but that work for me , are of type text
My index:
<div class="container" ng-app="todoApp" ng-controller="todoController">
<h1>Profile</h1>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Foto de perfil: </h4>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type='File' name="photo" ng-model="todo.photo" class="image-upload"required/>
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="">Nombre del bar: </label>
<input type='text' ng-model="todo.name" class="form-control" required/>
</div>
<button class="btn btn-primary btn-block" ng-click="addTodo()">Guardar</button>
<i ng-show="loading" class="fa fa-spinner fa-spin"></i>
</div>
</div>
My route:
Route::get('admin/bar', 'BarsController#index');
Route::resource('/bar', 'BarController');
My model:
namespace App;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Eloquent\Model;
class bar extends Model
{
protected $fillable = array('name','photo', 'cover',
'description', 'phone', 'email','direction', );
public function setPhotoAttribute($photo)
{
$file = array('image' => Input::file('photo'));
$destinationPath = 'images/bar/profile';
$extension = Input::file('photo')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension;
$this->attributes['photo'] = $fileName;
Input::file('photo')->move($destinationPath, $fileName);
}
BarsController:
public function index()
{
return view ('bar.index');
}
BarController:
public function store() {
$todo = \Auth::user()->bars()->create(Request::all());
return $todo;
}
App.js ( Angular JS ):
var app = angular.module('todoApp', function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
// Todo Controller ,...
app.controller('todoController', function($scope, $http) {
$scope.todos = [];
$scope.loading = false;
$scope.init = function() {
$scope.loading = true;
$http.get('/bar').
success(function(data, status, headers, config) {
$scope.todos = data;
$scope.loading = false;
});
}
$scope.addTodo = function() {
$scope.loading = true;
$http.post('/bar', {
name: $scope.todo.name,
description: $scope.todo.description,
phone: $scope.todo.phone,
email: $scope.todo.email,
direction: $scope.todo.direction,
photo: $scope.todo.photo,
cover: $scope.todo.cover
}).success(function(data, status, headers, config) {
$scope.todos.push(data);
$scope.todo = '';
$scope.loading = false;
});
};
$scope.updateTodo = function(todo) {
$scope.loading = true;
$http.put('/bar' + todo.id, {
title: todo.title,
done: todo.done
}).success(function(data, status, headers, config) {
todo = data;
$scope.loading = false;
});;
};
$scope.deleteTodo = function(index) {
$scope.loading = true;
var todo = $scope.todos[index];
$http.delete('/bar' + todo.id)
.success(function() {
$scope.todos.splice(index, 1);
$scope.loading = false;
});;
};
$scope.init();
});
I am using below code to upload image try this, I hope it works for you too.
<-- Front end file input -->
<input type="file" name="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
<-- Angular Controller's File -->
$scope.uploadavtar = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("/uploadavtar", fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).then(function successCallback(response) {
alert(response);
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
alert(response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
<-- In Route File -->
Route::post('/uploadavtar', 'UsersController#uploadavtar');
<-- In UsersController -->
public function uploadavtar(Request $request){
$user = JWTAuth::parseToken()->authenticate();
$user_id = $user->id;
$user_name = $user->first_name." ".$user->last_name;
$file = array('image' => Input::file('file'));
// setting up rules
$rules = array('image' => 'required',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return "validation failed";
}else {
// checking file is valid.
if (Input::file('file')->isValid()) {
$destinationPath = 'assets/img'; // upload path
$extension = Input::file('file')->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
Input::file('file')->move($destinationPath, $user_name."_$user_id".".jpeg"); // uploading file to given path
// sending back with message
return 'Upload successfully';
}
else {
// sending back with error message.
return 'uploaded file is not valid';
}
}
}

how to get angularjs routeParams data into input from two different Database tables?

my database has two tables one for "Customers" and another for "Tripsheets".
I would like to call the routeParams data of Customers into Tripsheets.
I tried something like this, but it does'nt work
HTML
<div class="row mini-stat" ng-controller="TripsheetCtrl1" >
<div class="col-md-4">
<div class="input-group m-bot15">
<span class="input-group-addon btn-white"><i class="fa fa-user"></i></span>
<input ng-model="tripsheet.tripsheet_num" type="text" class="form-control input-lg" >
</div>
</div>
JS
var urltd = 'http://localhost/tripsheets';
app.factory('tripsheetFactoryd', function ($http) {
return {
getTripsheetsd: function () {
return $http.get(urltd + '/all');
},
addTripsheetd: function (tripsheet) {
return $http.post(urltd, tripsheet );
},
deleteTripsheetd: function (tripsheet) {
return $http.delete(urltd + '?id=' + tripsheet.id);
},
updateTripsheetd: function (tripsheet) {
return $http.put(urltd + '?id=' + tripsheet.id, tripsheet);
}
};
});
var url = 'http://localhost/customers';
app.factory('customerFactory', function ($http) {
return {
getCustomers: function () {
return $http.get(url + '/all');
},
addCustomer: function (customer) {
return $http.post(url, customer);
},
deleteCustomer: function (customer) {
return $http.delete(url + '?id=' + customer.id);
},
updateCustomer: function (customer) {
return $http.put(url + '?id=' + customer.id, customer);
}
};
});
app.controller('TripsheetCtrl1', function ($scope, tripsheetFactoryd, customerFactory, $routeParams) {
$scope.tripsheets = [];
tripsheetFactoryd.getTripsheetsd().then(function(data){
$scope.tripsheets = data.data;
$scope.tripsheet = {
tripsheet_num: "{{customers[whichItem].name}}"
};
$http.get(url + '/all').success(function(data) {
$scope.customers = data;
$scope.whichItem = $routeParams.itemId;
if ($routeParams.itemId > 0) {
$scope.prevItem = Number($routeParams.itemId)-1;
} else {
$scope.prevItem = $scope.customers.length-1;
}
if ($routeParams.itemId < $scope.customers.length-1) {
$scope.nextItem = Number($routeParams.itemId)+1;
} else {
$scope.nextItem = 0;
}
});
});
});
Since you're making the calls in the same controller TripsheetCtrl1 you will be sharing the same $scope...so first populate $scope.customers and $scope.whichItem by calling the $http.get and then use those values in your getTripsheetsd().
app.controller('TripsheetCtrl1', function ($scope, tripsheetFactoryd, customerFactory, $routeParams) {
$scope.tripsheets = [];
customerFactory.getCustomers().success(function(data) {
$scope.customers = data;
$scope.whichItem = $routeParams.itemId;
$scope.tripsheet = {
tripsheet_num: $scope.customers[$scope.whichItem].name;
};
if ($routeParams.itemId > 0) {
$scope.prevItem = Number($routeParams.itemId)-1;
} else {
$scope.prevItem = $scope.customers.length-1;
}
if ($routeParams.itemId < $scope.customers.length-1) {
$scope.nextItem = Number($routeParams.itemId)+1;
} else {
$scope.nextItem = 0;
}
});
tripsheetFactoryd.getTripsheetsd().then(function(data){
$scope.tripsheets = data.data;
});
});

Categories

Resources