I tried to create a small service for adding and getting. I have successfully added details when I click register(form details are added)in one controller. Now I want that form details in another controller, but I'm not getting it. I'm able to get that details in that get function and able to print in console but I cannot pass them to html
Here is my HTML:
<div id="inputArea" style="border: 1px solid blue;width: 800px;height: 45px;margin: auto;" ng-controller="MyFormCtrl">
<form name="myForm" ng-submit="register()">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter first name" ng-model="user.fname">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter last name" ng-model="user.lname">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter designation" ng-model="user.designation">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter company" ng-model="user.company">
<input type="submit" style="float:right;" value="Register"> </form>
</div>
<div id="box" style="position: relative;top:200px;margin: auto;border:1px solid red;width:180px;height:90px;" ng-controller="DetailsConroller">
<input type="button" ng-click="getDetails()" value="get">
<!-- <input type="submit" style="" value="get">-->
<ul>
<li ng-repeat="x in employees"> {{ x.fname }} </li>
</ul>
</div>
my js:
var app = angular.module('myApp', []);
--->service for adding and get
app.service('employeeService', ['$rootScope', function ($rootScope) {
var employeeList = [];
return {
employeeList: []
, // var employeeList = [],
add: function (item) {
employeeList.push(item);
console.log('employeeList', employeeList);
}
, get: function () {
// console.log('in to get employeeList',employeeList);
return employeeList
}
};
}])
---->> COntroller to Add:
app.controller('MyFormCtrl', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.user = {
fname: ''
, lname: ''
, designation: ''
, company: ''
};
$scope.register = function () {
console.log('User clicked register', this.user);
employeeService.add(this.user);
//employeeService.updateUserData().set($rootScope.user);
};
}]);
--->>second controller to get:
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
var employees = [];
$scope.getDetails = function () {
// console.log('User clicked register', this.user);
employees = employeeService.get();
console.log('User in to get', employees[0].fname);
return employees;
};
}]);
what am I doing wrong here?
You need to have a $scope variable,
Change your Controller like this,
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.employees = [];
// console.log('User clicked register', this.user);
$scope.employees = employeeService.get();
console.log('User in to get', employees[0].fname);
}]);
Related
Hi i am beginner for angularJS and i am showing angular-ui modal form when click on button and have to add new user but i am really confusing how to handle and how to do this scenario and i tried below code but its not working can some one help me better way to do this
My requirement i want to open modal form for adding new user and when i click save button i need to add that new user in my array
main.js
// create the module, pass in modules it depends on
var app = angular.module('myApp', ['ui.bootstrap']);
// $modal service is now available via the ui.bootstrap module we passed in to our module
app.controller('myController', ['$scope', '$uibModal', '$log',
function ($scope, $uibModal, $log) {
$scope.newUser = {};
$scope.info = "";
$scope.users = [
{ username: "rimon", fullName: "Md. Mamunur Rashid Rimon", email: "rimonmath#gmail.com" },
{ username: "shamim", fullName: "Md. Tamim Hossain", email: "shamim#gmail.com" },
{ username: "tamim", fullName: "Tamim Iqbal", email: "tamim#gmail.com" }
];
$scope.addUser = function () {
var modalInstance = $uibModal.open({
templateUrl: 'add_user.html',
controller: 'ModalInstanceCtrl',
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
$scope.saveUser = function () {
console.log("Saving...");
$scope.users.push($scope.newUser);
$scope.info = "New User Added Successfully!";
$scope.newUser = {};
};
$scope.selectUser = function (user) {
$scope.clickedUser = user;
};
$scope.deleteUser = function () {
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function () {
$scope.info = "";
};
}]);
angular.module('myApp').controller('ModalInstanceCtrl', function ($scope,$uibModalInstance) {
$scope.saveUser = function () {
alert("You clicked the ok button.");
$uibModalInstance.close();
};
$scope.close = function () {
alert("You clicked the cancel button.");
$uibModalInstance.dismiss('cancel');
};
});
Form.html
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">New User Registration</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Username" ng-model="newUser.username">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Email" ng-model="newUser.email">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Full Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Full Name" ng-model="newUser.fullName">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="saveUser();">Save</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="close()">Close</button>
</div>
</div>
From what I see, your problem lies in your declaration of FormController.js please try to change this code :
app.controller('ModalInstanceCtrl', ['$scope','$modalInstance',function ($scope, $modalInstance) {
$scope.close = function () {
$modalInstance.dismiss('cancel');
};
$scope.saveUser = function(){
//SUBMIT FORM HERE
}
}]);
for this one :
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($uibModalInstance, data)
{
var pc = this;
pc.data = data;
pc.ok = function () {
//{...}
alert("You clicked the ok button.");
$uibModalInstance.close();
};
pc.cancel = function () {
//{...}
alert("You clicked the cancel button.");
$uibModalInstance.dismiss('cancel');
};
});
From your code I noticed that:
Your declaration of the modal controller misses the name of the main module app which sometimes is required.
you are using '$modalInstance' instead of $uibModalInstance
For further reference go here. Please try these changes and let me know if it works!
I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!
HTML:
<section ng-controller="MainController">
<form action="" class="form-inline well well-sm clearfix" >
<span class="glyphicon glyphicon-search"></span>
<input type="text" placeholder="Search..." class="form-control" ng-model="city" />
<button class="btn btn-warning pull-right" ng-click="search()"><strong>Search</strong></button>
</form>
<h1>{{fiveDay.city.name}}</h1>
<div ng-repeat="day in fiveDay.list" class="forecast">
<div class="day">
<div class="weekday">
<p>{{ day.dt*1000 | date}}</p>
<!-- <p>{{ parseJsonDate(day.dt)}}</p> -->
</div>
<div class="weather"><img ng-src="http://openweathermap.org/img/w/{{day.weather[0].icon}}.png"/></div>
<div class="temp">{{day.weather[0].description}}</div>
<div class="temp">Max {{ day.main.temp_max }}°</div>
<div class="temp">Min {{ day.main.temp_min }}°</div>
</div>
</div>
</section>
JS:
var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
forecast.city="orlando";
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
City is a variable part in your forecast factory so need to pass it as an argument in function will be the recommended for you
Try this
var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
var city = "orlando";
forecast.getWeatner(city).success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
var key = "a1f2d85f6babd3bf7afd83350bc5f2a6";
return {
getWeatner: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + '&APPID=' + key + '&units=metric&cnt=5');
}
}
}]);
增加参数 callback , 回调:JSON_CALLBACK
$http.jsonp("http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5&callback=JSON_CALLBACK").success(function(data){ ... });
here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...
I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});
I use the following ng-model with ng-repeat and I tried to access the data in my controller but it seems that the data cant be accessed there.
<div ng-controller="myCtrl" class="container">
<fieldset data-ng-repeat="contact in choices">
<input class="form-control" ng-model='contact.firstname'>
<input class="form-control" ng-model='contact.lastname'>
<input class="form-control" ng-model='contact.email'>
<input class="form-control" ng-model='contact.contact'>
<input class="form-control" ng-model='contact.adress'>
<input class="form-control" ng-model='contact.city'>
<input class="form-control" ng-model='contact.state'>
<button class="btn btn-primary" ng-click="addcontact()">Add</button></td>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
</div>
</div>
And use the following ng-app
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.choices = [{
id: 'choice1'
}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id': 'choice' + newItemNo
});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length - 1;
$scope.choices.splice(lastItem);
};
var refresh = function() {
$http.get('/contactlist').success(function(response) {
console.log("in m new controler now");
$scope.contactlist = response;
$scope.contact = "";
});
};
refresh();
$scope.addcontact = function() {
console.log($scope.contact);
$http.post('/contactlist', $scope.contact).success(function(response)
{
console.log(response);
refresh();
});
};
});
I can't access the data in $scope for the dynamically added controls through ng-repeat
In order to acess the data you should use
$scope.choices[index]
Index is the number of index you want to acces
I am using basic angular.js concept to show and hide a div. For some reasons I am unable to make it work.
While Uploading a file I am showing a div 'myFormSpinner' on the basis of registerStart value. I am creating a phone gap app.
Could someone please help me in finding the issue. Apart from showing/hiding div everything works fine. Below is the code snippet:
<div class="row" ng-controller="RegisterCtrl">
<div id="myFormSpinner" ng-show="registerStart">
<img src="img/ajax-loader.gif">
</div>
<div class="col-md-8">
<form class="ng-pristine ng-invalid ng-invalid-required" style="margin-top:5%;">
<div class="col-md-6">
<input class="form-control " type="text" ng-model="registerData.Email" id="Email" name="Email" required placeholder="Email">
</div>
<div class="col-md-offset-1 col-md-10 ">
<input type="submit" ng-click="register()" value="Register" class="btn btn-default btn-primary">
</div>
</form>
</div>
event.controller('RegisterCtrl', ['$scope', '$state', '$q', '$http', 'eventService', 'authService', '$stateParams', '$rootScope', 'tokenService', 'imageService', 'spinnerService', 'appBackgroundService',
function ($scope, $state, $q, $http, eventService, authService, $stateParams, $rootScope, tokenService, imageService, spinnerService, appBackgroundService) {
var userNumber = 0;
$scope.mediaUploadStart = false;
$scope.eventId = $state.params.id;
$scope.register = function () {
$scope.registerStart = true;
console.log('scope.Pic=' + $scope.pic);
if ($scope.registerData.Email) {
spinnerService.show('myFormSpinner');
$scope.mediaUploadStart = true;
var paramOptions = {
eventId: $state.params.id,
email: $scope.registerData.Email,
fb: {},
number: userNumber,
provider: "Form"
};
uploadPicAndData(paramOptions).then(function (result) {
var data = JSON.parse(result);
$scope.registerStart = false;
appBackgroundService.disableBackgroundMode();
},
function (error) {
spinnerService.hide('myFormSpinner');
$scope.registerStart = false;
appBackgroundService.disableBackgroundMode();
});
$scope.mediaUploadStart = false;
spinnerService.hide('myFormSpinner');
}
};
}])
You are setting the $scope element in an async mode.
the digest cycle is not able to determine that a change has been made to the scope element in an async mode.
You should use $apply to activate the digest cycle.
$scope.$apply(function () { $scope.registerStart = false; });
Read more about $apply here: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html