How to set data to a service function in AngularJS ng-click - javascript

I am trying to persist information inside a service so that I can access the data across controllers. Here is what I tried :
HTML:
<div ng-app="myApp">
<div ng-controller="ControllerOne as one">
<h2>ControllerOne:</h2>
<table>
<tbody>
<tr ng-repeat="emp in EmployeeInfo">
<td>{{emp.name}}</td>
<td>{{emp.hireDate}}</td>
<td><a class="btn-sm btn-primary pull-right" ng-click="storeIds({{emp.idUser}})" >E-Verify</a></td>
</tr>
</tbody>
</table>
Change testService.loginName: <input type='text' ng-model='one.myService.UserId'/> </br></br>
myName: {{one.myService.UserId}}
</div>
<hr>
<div ng-controller="ControllerTwo as two">
<h2>ControllerTwo:</h2>
myName: {{two.myService.UserId}}
</div>
</div>
JS:
app.service('testService', function(){
this.UserId= uId;
});
app.controller('ControllerOne', function($scope, testService){
$scope.storeIds = function (userid) {
// HERE I want to call the testService and set the value.
}
this.myService = testService;
});
app.controller('ControllerTwo', function($scope, testService){
this.myService = testService;
});

have you tried looking into using $rootScope?
app.controller('ControllerOne', function($scope, rootScope, testService){
$scope.storeIds = function (userid) {
// HERE I want to call the testService and set the value.
}
$rootScope.myService = userid;
});
app.controller('ControllerTwo', function($scope, ,rootScope, testService){
//rootScope.myService will now equal whatever the userid was in the other controller.
//I skipped using the service
});

Related

Edit input form in angularjs wetheen component

i am trying to edit form whit angularjs. The thing is i can t share data between shop.component and edit component.
I do an ng-repeat to get info from a service, and then when i click edit buttom in the shop component, is undefined on edit component.
here is my code.
shop.html
<tbody class="table-hover">
<tr ng-repeat="(id,local) in $ctrl.locals | orderBy:sortType:sortReverse | filter: $ctrl.name | filter:$ctrl.address">
<td>{{local.name}}</td>
<td>{{local.address}}</td>
<td>{{local.phone}}</td>
<td>
<button ng-click="$ctrl.editShop(id)" class="button expand success">Edit</button>
</td>
</tr>
</tbody>
shop.component
angular.module('app')
.component('articleComponent', {
bindings: {
name: '<',
address: '<'
},
templateUrl : 'app/articles/articles.html',
controller : function(deliveryService, $location, $scope){
this.locals = deliveryService.getDetailLocals()
this.sortType= 'name';
this.sortReverse = true;
this.editShop = function(id){
$location.path("/edit/" + id)
}
}
})
edit.html
<form>
<fieldset>
<legend>{{ textButton }}</legend>
<div class="row">
<div class="large-12 columns">
<label>name</label>
<input type="text" placeholder="name" ng-model="local.name" required>
</div>
</div>
<div class="row">
<div class="large-4 columns">
<label>Adress</label>
<input type="text" placeholder="Edad" ng-model="local.adress" required>
</div>
</div>
<button type="submit" class="button large-12">{{ textButton }}</button>
</fieldset>
</form>
edit.component.js
angular
.module('app')
.component('editComponent', {
bindings: {},
templateUrl: 'app/edit/edit.html',
controller: function ($scope, $routeParams) {
$scope.textButton = "Edit user";
console.log($scope.local) // --> undefined
console.log($routeParams) // --> {id:'0'}
}
})
service.js
angular.module('app')
.service('deliveryService', function(){
this.getDetailLocals = function () {
return [
{name: 'Bar BQ', address: 'St. 12 nro 1587', phone:'456 715 42'},
{name: 'XXX Bar', address: 'St. 44 nro 1548', phone:'156 715 42'}
]
}
})
I know if i send 'local' in the ng-click function send the whole object, what i loose the id number generated with the ng-repeat...
any help?
thanks!!
Pil
You can anytime get the value by using deliveryService, you can call getDetailLocals method as like what you were calling inside article-component.
controller: function ($scope, $routeParams, deliveryService) {
$scope.textButton = "Edit user";
var locals = deliveryService.getDetailLocals();
var selectedItem = locals.filter(function(local) {
return local.id == $routeParams.id
})
console.log(selectedItem && selectedItem[0])
}

Angular js: Iterate over list in view (ng-foreach)

I am getting json data in server response and return that to $scope.questions
I want to access this questions data in step1.html file.
app.js
(function () {
"use strict";
var app = angular.module("autoQuote",["ui.router","ngResource"]);
app.config(["$stateProvider","$urlRouterProvider", function($stateProvider,$urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("step1", {
url : "/",
templateUrl : "easyquote/step1.html",
controller: "questionsCtrl",
})
.state("step2", {
url : "/step2",
templateUrl : "easyquote/step2.html",
controller: "questionsCtrl",
})
}]
);
}());
autoQuoteCtrl.js
(function () {
"use strict";
angular
.module("autoQuote")
.controller("questionsCtrl",["$scope","$http","$state",questionsCtrl]);
function questionsCtrl($scope,$http,$state) {
$http.get('rc1/getQuestions/' + $state.current.name)
.then(function(response) {
$scope.questions = response.data;
});
}
}());
step1.html
<div ng-controller="autoQuoteCtrl">
<form name="DTOstep1" ng-submit="onSubmit()">
<label>Email: </label><input type="text" name="email" id="email" />
<br><br>
<table ng-repeat="questions in que">
<tr>
<td>{{que.QuestionData._attributeName}}</td>
<td></td>
<tr>
</table>
<input type="submit" value="Save" />
</form>
</div>
Your usage of ng-repeat is the wrong way round. It should be like this:
<table ng-repeat="que in questions">
HTML
<table ng-repeat="questions in que">
<tr>
<td>{{questions._any_name}}</td>
<td></td>
<tr>
</table>

send the id from the table to the controller with angularjs

I wonder how can I send the id of the selected row from my table to the controller when I try to show the details of these row,this is my code:
app.js:
.controller("etudmodifCtrl", ["$scope", "$http", "filterFilter", "$rootScope", "logger", "$filter", "$modal", "$log", function ($scope, $http, filterFilter, $rootScope, logger, $filter, $modal, $log) {
$http({
method: 'GET',
url: 'http://localhost:50001/api/Students/' + $scope.store.id
}).success(function (data) {
$scope.firstname = data.FirstName;
$scope.lastname = data.LastName;
$scope.email = data.Email;
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
$scope.open = function () {
var modalInstance;
modalInstance = $modal.open({
templateUrl: "myModalContent1.html",
controller: "ModalInstanceCtrl",
resolve: {
items: function () {
return $scope.items
}
}
}), modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem
}, function () {
$log.info("Modal dismissed at: " + new Date)
})
}
}])
my html code:
<table class="table table-responsive table-hover" ng-controller="etudmodifCtrl">
<tr ng-repeat="store in currentPageStores">
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
<td align="center">{{store.Email}}</td>
<td align="center">{{store.Class}}</td>
<td align="center">
<script type="text/ng-template" id="myModalContent.html">
< div class ="modal-header">Modify Informations</div><div class = "modal-body modal-dialog modal-lg3" data-ng-controller = "etudmodifCtrl">
<div class="panel-body" >
<div class="col-md-6">
<div class="form-group">
<label for="" class="col-sm-2">FirstName</label>< div class = "col-sm-10"><input type = "email" class ="form-control" ng-model = "firstname">
</div>
</div >< /div>
<div class="form-group">
<label for="" class="col-sm-2">LastName</label>< div class = "col-sm-10"><input type = "email" class ="form-control" ng-model = "lastname">
</div>
</div >< /div>
<div class="form-group">
<label for="" class="col-sm-2">Email</label>< div class = "col-sm-10"><input type = "email" class ="form-control" ng-model = "email">
</div>
</div >< /div>
</script>
</td>
</tr>
</table>
<button type="button" onclick="window.location = '" aria-label="Center Align" ng-click="open()" data-toggle="modal" data-target=".bs-example-modal-lg">Modify</button>
I try to send the id via the open function but I get a syntax error
thanks for help
In button bg-click pass the id by using ng-click="open(store.storeId)" complete code
<button type="button"
aria-label="Center Align"
ng-click="open(store.storeId)"
data-toggle="modal"
data-target=".bs-example-modal-lg">Modify</button>
And change your open function to accept a parameter like this
$scope.open = function (id) {
............
............
}
for more detail, who to pass value from controller to model controller see this Pass parameter to modal

AngularJS : View doesn't update when a value in $scope changes

I have an html file with a view that gets it's values from an AngularJS scope.
<form ng-controller="EmployeesController as emp" class="signed-in" ng-submit="logOutUser()">
<div class="row">
<div class="col-md-10 text-left">
<h5>Your Games, {{emp.username}}</h5>
</div>
<div class="col-md-2">
<button class="btn btn-md btn-primary btn-block" type="submit">Log Out</button>
</div>
</div>
<div class="row store">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Games To Buy</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Game Name</th>
<th>Game Status {{what}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="game in emp.games">
<td>{{game}}</td>
<td>
<button ng-click="buyGame(game.gameId)" type="button" class="btn btn-sm btn-primary btn-block" href="#">Buy</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</form>
.
And the js file :
var app = angular.module("MyApp", ['ngRoute']);
app.controller("EmployeesController", function($scope, $http) {
this.games = [{gameName: 'aaa', gameId: '1'},{gameName: 'aaa', gameId: '1'},{gameName: 'aaa', gameId: '1'}];
this.ownedGames = [];
var that = this;
$scope.sellGame = function(gameId) {
var index = that.ownedGames.indexOf(gameId);
that.ownedGames.splice(index, 1);
$.jStorage.set(that.username, that.ownedGames);
}
$scope.$on('$viewContentLoaded', function() {
if($.jStorage.get('Employee') == null)
$scope.logged = false;
else
$scope.logged = true;
$http.get('employees.json').
success(function(data, status, headers, config) {
that.games = data.games;
that.username = $.jStorage.get('Employee');
if($.jStorage.get(that.username) != null)
that.ownedGames = $.jStorage.get(that.username);
});
});
});
Ok. So basically what the problem is, is that the emp.games variable is empty. First of all it gets commented in the rendered HTML page, and second when i debug the page the variable emp.games is empty. Yet the variable that emp.games is supposed to get its values from, the $scope.games is filled with values as it should be. So the problem is that my emp.games doesn't see that $scope.games was updated in that http request, so IT doesn't update. I googled as much as i could and found out that i should use $scope.apply, but wherever i used it i got the error $digest already in progress... any ideas?
Thanks
Try check diggest
if (!$scope.$$phase) {
$scope.$apply(function () {
that.games = data.games;
})
}
else
that.games = data.games;
Or you can inject $timeout service and use it like this, it will be better.
$timeout (function () {
that.games = data.games;
}, 0)
Your controller definition is not valid, please use like this.
app.controller("EmployeesController", ['$scope','$http','$timeout', function($scope, $http, $timeout){
//....
}]

How to load data in ngDialog

I have a requirement where I need to open a dialog from a jsp page and while opening the dialog, I need to load it with some prepopulated data from the server (using an AJAX call). If I make the AJAX call before opening the dialog, I get the data but the dialog loads like a new page. If I try to get the data in the new controller, the dialog still does not reflect the data. What should I use to make sure the dialog reflects the data that I am getting from the server
<div class="container-fluid" ng-controller="EditUserController">
<div class="text-center container-fluid">
<label class="sub-header">Edit User: {{userEmail}}</label>
</div>
<form action="editUser" method="post" name="editForm">
<div>
<div class="pull-right">
<label>Delete User</label><br> <a href="#"
class="btn btn-block btn-sm btn-danger" ng-click="deleteUser(userEmail)">{{userEmail}}</a>
</div>
<div>
<label>Change Role</label>
</div>
<div>
<label>
<input type="checkbox" ng-model="superVisor" name="superVisorFlag"
ng-true-value="1" ng-false-value="0" value="${existingUser.superVisorFlag}">
Make a Supervisor</label>
</div>
<div>
<input type="text" class="form-control" ng-model="email"
name="emailAddress" ng-disabled = "true"
ng-options="email for email in userEmail"
value="${existingUser.emailAddress}"
placeholder="Enter New User Email Address" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="firstName"
name="firstName" value="${existingUser.firstName}"
placeholder="Enter First Name" bs-typeahead>
</div>
<div>
<input type="text" class="form-control" ng-model="lastName"
name="lastName" value="${existingUser.lastName}"
placeholder="Enter Last Name" bs-typeahead>
</div>
<div>
Save Changes
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="<c:url value="/resources/scripts/admin.js"/>"></script>
The above is a jsp for the dialog. Below is my js file -
var app = angular.module('scc-admin', [ 'ngDialog', 'mgcrea.ngStrap' ]);
app.factory("UserList", function() {
var UserList = {};
UserList.data = [ {
userId : 111,
userFirstName : "xxx",
userLastName : "yyy",
userEmail : "xxx.yyy#zzz.com",
userRole : "Admin"
}, {
userId : 222,
userFirstName : "second",
userLastName : "last",
userEmail : "second.last#zzz.com",
userRole : "Manager"
}];
return UserList;
});
app.controller('UserSettingsController', function($scope, ngDialog, UserList,$http) {
// variable for the bashboard list
$scope.userList = UserList;
$scope.editUser = function(userEmail) {
$scope.userEmail = userEmail;
ngDialog.open({
template : 'editUser' ,
className : 'ngdialog-theme-default',
controller : 'EditUserController',
closeByEscape : true,
scope : $scope
});
};
$scope.addUser = function() {
ngDialog.open({
template : 'addUser',
className : 'ngdialog-theme-default',
controller : 'AddUserController',
closeByEscape : true,
scope : $scope
});
};
});
app.controller('EditUserController', function($scope, ngDialog, $http) {
ngDialog.template = $scope.output;
ngDialog.$modelValue = $scope.output;
var responsePromise = $http.get("initUser?email=" + $scope.userEmail);
responsePromise.success(function(data, status, headers, config) {
$scope.output = data;
console.log(data);
});
console.log($scope);
$scope.deleteUser = function(){
$scope.cfdump = "";
var str = {emailAddress : $scope.userForm.emailAddress.$modelValue};
str = JSON.stringify(str);
var request = $http({
method: 'post',
url: "deleteUser?formData=" + str,
data: ({formData:str})
});
request.success(function(html){
alert("success");
});
request.error(function(errmsg){
alert("Unable to delete user");
});
}
});
I am opening a dialog in usersettings controller and trying to load it with default data. I tried setting the new dialog's template to the output of the AJAX call, it did not work. What am I missing here?
After consulting the documentation, I learned following solution. It should work for you like it did for me.
To pass data (JSON Object) for ng-model inside the ngDialog, you can declare your ngDialog as following.
ngDialog.open({
template: 'my-template.html',
className: 'ngdialog-theme-plain',
data: $scope.myJSONObject
});
Now, with the above part done, you need to bind the data in your popup ngDialog, so go and put ngDialogData.myJSONObjectFieldName in your ng-model.
Consider following example for further elaboration. We assume that we have myJSONObject as following.
myJSONObject={
first_name: 'John',
last_name: 'Doe'
};
To use first_name inside your ngDialog's ng-model, simply put ng-model="ngDialogData.first_name".
To check whether the controller(VM) data is received in Modal Dialog use this
<pre>{{vm|json}}</pre>
Module and Controller:
var app = angular.module("DemoApp",['ngDialog']);
app.controller("DemoController",["$rootScope","ngDialog","productService",function($rootScope,ngDialog,productService){
var vm=this;
$rootScope.ngDialog = ngDialog; // to close Dialog using "ngDialog.close();" in ProductDialog.html
/* vm.products=[{brand:"Apple", price:60000, os:"iOS"},
{brand:"Samsung", price:35000, os:"Android"},
{brand:"Microsoft Lumia", price:30000, os:"Windows 10"}
];
*/
vm.getProductDetails=function() {
productService.getData().then(function (response) {
if (response.data) {
vm.products=response.data;
vm.ProdDialog();
}
});
};
vm.productPopup = function(x){
ngDialog.open({
template: 'ProductDialog.html',
className:'ProductDetailsDialog'
scope:$scope,
data:x,
closeByDocument:true
});
}
vm.getProductDetails();
}]);
Service:
app.factory("productService",["$http",function($http){
return {
getData: function() {
return $http.get("http://xxxxxxx/xxx/xxxxx");
}
};
}]);
DemoController.html
/* <table>
<tr>
<th>Brand</th>
<th>Price</th>
<th>OPerating System</th>
<th>Open ngDialog</th>
</tr>
<tr ng-repeat="x in vm.products">
<td ng-bind="x.brand"></td>
<td ng-bind="x.price| currency:"₹":2"></td>
<td ng-bind="x.os"></td>
<td><button ng-click="vm.productPopup(x)"></button></td>
</tr>
</table>
*/
ProductDialog.html:
<div class="ProductDetailsDialog">
<div class="ngdialog-content" role="document">
<div class="modal-header">
<button type="button" class="close" ng-click="ngDialog.close();">×</button>
<h4 class="modal-title">Product Detials</h4>
</div>
// <pre>{{vm|json}}</pre> //
<div class="modal-body">
<h4>Brand:<span ng-bind="ngDialogData.brand"></span></h4>
<h4>Price:<span ng-bind="ngDialogData.price | currency:"₹":2"></span></h4>
<p>Operating System:<span ng-bind="ngDialogData.os"></span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default">OK</button>
</div>
</div>
</div>

Categories

Resources