Edit input form in angularjs wetheen component - javascript

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])
}

Related

AngularJS: Get attribute value in controller

i am a newbie of angularJS, i just want to ask how can i get value of on-success attribute which will have a JSON object on a successful upload request.
"on-success" attribute exists on post-creator.template.html page.
index.html
<body>
<div>
<post-creator post-id="0"></post-creator>
</div>
</body>
This a post-creator.template.html
<form role="form">
<div class="form-group float-label-control">
<label>Title</label>
<input type="text" placeholder="Name" class="form-control" ng-model="model.post.title">
</div>
<div upload-button
url="/user_uploads"
on-success="onSuccess(response)"
on-error="onError(response)"
ng-model="onSuccess(response)"
>Upload</div>
<div class="text-center">
<button type="button" class="btn btn-default" ng-click="model.save(model.post)">Save</button>
</div>
</form>
And this is post-creator.component.js:
(function () {
"use strict";
var module = angular.module(__appName);
function controller($http) {
var model = this;
model.post = null;
model.save = function (post) {
//get on-success value here
//console.log(model.onSuccess);
}
}
module.component("postCreator", {
templateUrl: "components/post-creator/post-creator.template.html",
bindings: {
category: "<",
postId: "<",
subCategory: "<"
},
controllerAs: "model",
controller: ["$http", controller]
});
}());
you can inject $element to your controller and get attributes binded to your directive by $element[0].attributes.
function controller($http, $element) {
var attrs = $element[0].attributes;
// you own logic
}

Controller reading component data

My idea is to create a big form from separated components. So this is my main template:
<form novalidate>
<div class="row">
<user></user>
</div>
<button type="button" class="btn btn-default" ng-click="submit()"> Submit </button>
</form>
and its controller (the template is binded from ui route config to the controller)
(function () {
'use strict';
angular.module('app')
.controller('formCtrl', formCtrl);
function formCtrl ($scope) {
$scope.submit = function() {
console.log("read data");
}
}
})();
Now, the user component:
(function () {
'use strict';
var module = angular.module('app.user');
module.component("user", {
templateUrl: "app/user/user.html",
controllerAs: "model",
controller: function () {
var model = this;
model.user = {};
}
});
})();
and the user template:
<form novalidate>
<form-group>
<label for="inputUser"> Name <label>
<input ng-model="model.user.name" id="inputUser" type="text" placeholder="User"/>
</form-group>
<form-group>
<label for="inputUser"> Email <label>
<input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email"/>
</form-group>
<div>
{{model.user | json}}
</div>
</form>
Now I want to be able to read user data when the user do the submit. How can I do it?
When using components, depending on the type of component (smart or dumb), you have to emit an output to the parent controller to handle such thing. But in this case, you can use ngModel to handle a model and change it on the parent from within the component. For example:
Working snippet:
angular.module('app', [])
.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.submit = function() {
console.log($scope.user);
}
})
.component("user", {
bindings: {
user: '=ngModel'
},
templateUrl: "app/user/user.html",
controllerAs: "model",
controller: function() {}
});
angular.element(function() {
angular.bootstrap(document, ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<form novalidate ng-controller="formCtrl">
<div class="row">
<user ng-model="user"></user>
</div>
<button type="button" class="btn btn-default" ng-click="submit()">Submit</button>
</form>
<script type="text/ng-template" id="app/user/user.html">
<form novalidate>
<div>
<label for="inputUser">Name
<label>
<input ng-model="model.user.name" id="inputUser" type="text" placeholder="User" />
</div>
<div>
<label for="inputUser">Email
<label>
<input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email" />
</div>
<div>
{{ model.user | json }}
</div>
</form>
</script>
A possible solution would be $$childTail. So if I want to access to user:
$scope.$$childTail.model.user

why Ng Repeat is not working if button invoked from a different form?

I have a html table that contains an ng repeat directive and two button.The first one will open a modal that contains a new form and let me create my user and then when i click save it will add it to the list.The second one is in the same original form and do the add a user.
What i did not understand why when i click on the first button which is in a different form i can not update the ng repeat however for the second one it's possible.
This is the code:
homepage.jsp
<body ng-app="myApp">
<div class="generic-container" ng-controller="UserController as ctrl">
<div id="createUserContent.jsp" ng-include="createUserContent"></div>
<table>
<tr>
<td>
<button type="button" class="btn btn-primary"
ng-click="ctrl.openCreateUser()">Create</button>
</td>
</tr>
</table>
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in ctrl.users">
<td><span ng-bind="u.ssoId"></span></td>
<td><span ng-bind="u.firstName"></span></td>
<td><span ng-bind="u.lastName"></span></td>
<td><span ng-bind="u.email"></span></td>
</tr>
</tbody>
</table>
</div>
</body>
user_controller.js
'use strict';
App.controller('UserController', function ($scope, UserService, $window, $log, $uibModalStack,
$uibModal, $rootScope) {
var self = this;
self.users = [];
self.fetchAllUsers = function () {
console.log('----------Start Printing users----------');
for (var i = 0; i < self.users.length; i++) {
console.log('FirstName ' + self.users[i].firstName);
}
};
/**
this function will not work
**/
self.saveUser = function (user) {
self.users.push(user);
self.fetchAllUsers();
$log.log("saving user");
$uibModalStack.dismissAll();
};
/**
this function works fine
**/
self.addNewRow = function () {
var specialUser = {
id : 12,
firstName : 'john',
lastName: 'travolta',
homeAddress : {location:'chicago'},
email : 'trav#email.com'
};
self.users.push(specialUser);
$log.log("saving specialUser");
};
self.openCreateUser = function () {
var modalInstance = $uibModal.open({
animation : true,
templateUrl : 'createUserContent',
controller : 'UserController',
resolve : {
items : function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
self.fetchAllUsers();
});
createUserContent.jsp
<form role="form" ng-controller="UserController as ctrl" >
<div class="form-group">
<label for="FirstName">FirstName</label> <input type="FirstName"
ng-model="ctrl.user.firstName" class="form-control"
id="FirstName" placeholder="Enter FirstName" /> <label
for="lastName">lastName</label> <input type="lastName"
class="form-control" id="lastName"
ng-model="ctrl.user.lastName" placeholder="Enter lastName" />
<label for="email">Email address</label> <input type="email"
ng-model="ctrl.user.email" class="form-control" id="email"
placeholder="Enter email" />
</div>
<div class="form-group">
<label for="homeAddressLocation">Home Address</label> <input class="form-control"
ng-model="ctrl.user.homeAddress.location" id="homeAddressLocation"
placeholder="homeAddressLocation" />
</div>
<div class="form-group">
<label for="SSOId">SSOId</label> <input class="form-control"
ng-model="ctrl.user.ssoId" id="SSOId" placeholder="SSOId" />
</div>
<button type="submit" class="btn btn-default"
ng-click="ctrl.saveUser(ctrl.user)">Save</button>
<button type="submit" class="btn btn-default">Cancel</button>
</form>
Because of your modal template can't access your UserController object and doesn't show error because you used in modal template same controller so reloaded as new Ctrl doesn't refer parent Ctrl.
However better to use different controller and pass parent controller object to modal controller and then modal body can use all parent object. so you should pass parent object to modal controller.
When you include createUserContent.jsp popup file in your main file then no need to use ng-controller="UserController as ctrl" in your modal template you used in modalInstance controller : 'Ctrl',
like:
var modalInstance = $uibModal.open({
templateUrl: 'createUserContent.jsp',
controller: 'ModalCtrl', // ModalCtrl for modal
controllerAs:'modal', // as modal so no need to use in modal template
size: 'lg',
resolve: {
items: function () {
return $scope.items;
},
parent: function(){ // pass self object as a parent to 'ModalCtrl'
return self;
}
}
and ModalCtrl like:
.controller('ModalCtrl', ['parent', function (parent) {
this.parent = parent;
}]);
here used ModalCtrl for modal as modal so you can access parent object like: modal.parent.user
template like:
<form role="form" >
<div class="form-group">
<label for="FirstName">FirstName</label> <input type="FirstName"
ng-model="modal.parent.user.firstName" class="form-control"
id="FirstName" placeholder="Enter FirstName" />
.....
....
<button type="submit" class="btn btn-default"
ng-click="modal.parent.saveUser(modal.parent.user)">Save</button>
<button type="submit" class="btn btn-default">Cancel</button>
</form>
More details Visit PLUNKER DEMO

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

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