AngularJS: Passing data to modal from list - angularjs

I am currently learning how to build a MEAN webapp from scratch. Stuff goes quite well until this point but now i am stuck at trying to pass data from my list (ng-repeat) to my modal via ng-click=updatePerson(person). I have absolutely no clue why I can't access the data from the list. I tried like 20 variants to link the data between both scopes without any success.
This is my Controller:
angular.module('userCtrl', ['userService','ui.bootstrap'])
.controller( 'userController', function(User, $uibModal, $log, $scope) {
var vm = this;
User.all().success( function(data) {
vm.users = data;
})
vm.deleteUser = function(id) {
User.delete(id).success(function(data) {
User.all().success(function(data) {
vm.users = data;
});
});
};
vm.createUser = function() {
User.create(vm.userData).success(function(data) {
vm.userData = {};
User.all().success(function(data) {
vm.users = data;
});
});
};
vm.updateUser = function(selectedUser) {
$scope.selectedUser = selectedUser;
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'app/views/pages/modal.html',
resolve: {
user: function () {
return $scope.selectedUser;
}
}
});
modalInstance.result.then(function(selectedUser) {
$scope.selected = selectedUser;
});
};
});
My angular-router:
angular.module('appRoutes', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'app/views/pages/home.html',
controller : 'userController',
controllerAs : 'user'
})
.when('/users', {
templateUrl : 'app/views/pages/user.html',
controller : 'userController',
controllerAs : 'user'
});
$locationProvider.html5Mode(true);
});
My list:
<div class="btn-group">
<button type="button" class="btn-lg btn-default glyphicon glyphicon-plus" data-toggle="modal" data-target="#createModal"></button>
<table class="table table-nonfluid table-bordered table-striped" ng-show="user.users">
<thead>
<tr>
<th></th>
<th>Vorname</th>
<th>Nachname</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in user.users">
<td><button ng-click="user.deleteUser(person._id)" class="btn btn-default btn-lg glyphicon glyphicon-trash"></button></td>
<td>{{person.firstname}}</td>
<td>{{person.lastname}}</td>
<td>{{person.mail}}</td>
<td><button ng-click="user.updateUser(person)" class="btn btn-default btn-lg glyphicon glyphicon-trash"></button></td>
<!--<td><button class="btn-lg btn-default glyphicon glyphicon-option-horizontal" data-toggle="modal" data-target="#updateModal"></button> </td>-->
</tr>
</tbody>
</table>
<!--Create Modal-->
<div class="modal fade bs-example-modal-lg" id="createModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Neue Person</h4>
</div>
<form id="form1" ng-submit="user.createUser()">
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="control-label">Vorname</label>
<input type="text" class="form-control" ng-model="user.userData.firstname">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Nachname</label>
<input type="text" class="form-control" ng-model="user.userData.lastname">
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">E-Mail</label>
<input type="text" class="form-control" ng-model="user.userData.mail">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Schließen</button>
<button id="button1" type="submit" class="btn btn-primary">Person erstellen</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#button1').click(function() {
$('#createModal').modal('hide');
});
</script>
And here is my modal:
<div class="modal-content bs-example-modal-lg" role="dialog document">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Ändere Person</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="control-label">Vorname</label>
<input type="text" class="form-control" ng-model="person.firstname" placeholder={{person.firstname}}>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Nachname</label>
<input type="text" class="form-control" ng-model="person.firstname" placeholder={{person.lastname}}>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">E-Mail</label>
<input type="text" class="form-control" ng-model="person.firstname" placeholder={{person.mail}}>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Schließen</button>
<button id="button1" type="submit" class="btn btn-primary">Person ändern</button>
</div>
</div>

The user you're resolving won't be bound to the view automatically. You need a controller to do that. You can use the code below, or you can use controllerAs, but you'd have to update the modal's HTML accordingly.
vm.updateUser = function(selectedUser) {
$scope.selectedUser = selectedUser;
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'app/views/pages/modal.html',
resolve: {
user: function () {
return $scope.selectedUser;
}
},
controller: function($scope, user) {
$scope.user = user;
}
});
modalInstance.result.then(function(selectedUser) {
$scope.selected = selectedUser;
});
};

Related

Data edit - modal Bootstrap

I have a problem with editing data in the bootstrap modal.
The problem is that in the modal, only first record from the database is displayed.
Modal only displays the problem because it retrieves data from 1 record.
Could it show me something wrong with the code, that it only gets 1 record for me?
My code AngularJS:
controllersAdmin.controller('linkEdit', function( $scope, $http, $routeParams, $timeout){
var linkID = $routeParams.id;
$scope.id = linkID;
$scope.link = function( link ){
$http({
method: 'GET',
url: 'api/admin/links/get/' + linkID,
}).then(function (response){
$scope.link = response.data.records;
},function (error){
console.log('Blad we wczytywaniu danych');
});
}
$scope.saveChanges = function( link ){
$http({
method: 'POST', url: 'api/admin/links/update/', data: {'link' : link}},
).then(function (){
$scope.success = true;
},function (error){
console.log('Blad we wczytywaniu danych');
});
}
});
<tr ng-repeat="link in link">
<td>{{$index+1}}</td>
<td>{{link.links | limitTo:50}}...</td>
<td>{{ link.login }}</td>
<td>{{link.password}}</td>
<td>{{link.date}}</td>
<td>
<button ng-click="deleteLink(link, $index)" class="btn btn-danger">×</button>
<button data-toggle="modal" ng-click="edtlnk(link)" data-target="#edit-data" class="btn btn-primary">Edit</button>
<div class="modal fade" id="edit-data" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form method="POST" name="editlinke" role="form" ng-submit="saveChanges( link )">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Item</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" ng-model="link.login">
<input type="text" class="form-control" ng-model="link.password">
<input type="text" class="form-control" ng-model="link.links">
</div>
</div>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</td>
</tr>

How to get an html content in modal-body

I'm having trouble passing a html (form) for body modal.
Use the modal as a service, and have a standard template for the modal. If not past the template will of course use the default. And thus fail to repeat code.Then I wanted to go into the modal only the content that will be passed in scope.
modal.service.js
(function() {
var app = angular.module('app');
function ModalService($rootScope, $q, $modal) {
var defaultOptions = getModalDefaultOptions();
var service = {
showModal: showModal
};
return service;
function getModalDefaultOptions() {
return {
templateUrl: '/app/shared/modals/templates/modal.default.html',
closeButtonText: 'Fechar',
actionButtonText: 'OK',
headerTitle: 'Header default',
bodyContent: 'Conteúdo body modal',
showActionButton: true,
showCloseButton: true,
headerClass: ''
};
}
function showModal(customModalOptions) {
var deferred = $q.defer();
//Create temp objects to work with since we're in a singleton service
var tempModalOptions = {};
//Map modal.html $scope custom properties to defaults defined in service
angular.extend(tempModalOptions, defaultOptions, customModalOptions);
var scope = $rootScope.$new();
scope.modalOptions = tempModalOptions;
scope.modalOptions.ok = function(result) {
deferred.resolve();
modal.hide();
};
scope.modalOptions.close = function(result) {
deferred.reject();
modal.hide();
};
var modal = $modal({
scope: scope,
templateUrl: scope.modalOptions.templateUrl,
title: scope.modalOptions.headerTitle,
content: scope.modalOptions.bodyContent,
show: true
});
console.log(tempModalOptions);
return deferred.promise;
}
}
app.factory('ModalService', ModalService);
})();
modal.default.html
<div class="modal" role="dialog" tabindex="-1" data-type="Modal Default">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" data-ng-class="modalOptions.headerClass" ng-show="title">
<button class="close" ng-click="modalOptions.close();" type="button">×</button>
<h4 class="modal-title" ng-bind="modalOptions.headerTitle"></h4>
</div>
<div class="modal-body" ng-bind="modalOptions.contentTemplate">{{modalOptions.contentTemplate}}</div>
<div class="modal-footer">
<button class="btn btn-default" data-ng-click="modalOptions.close();" data-ng-show="modalOptions.showCloseButton" type="button">
{{modalOptions.closeButtonText}}</button>
<button class="btn btn-primary" data-ng-click="modalOptions.ok();" data-ng-show="modalOptions.showActionButton">
{{modalOptions.actionButtonText}}</button>
</div>
</div>
</div>
</div>
entidades.controller.js
(function() {
'use strict';
var app = angular.module('app');
app.controller('EntidadesController', EntidadesController);
function EntidadesController(EntidadeService, ModalService) {
var vm = this;
vm.entidades = JSON.parse(EntidadeService.getAll());
vm.openEditEntidades = function() {
ModalService.showModal({
headerClass: 'danger',
contentTemplate: '/app/modulos/entidades/views/edit-entidades.html'
})
.then(function() {
alert('Alert Modal 2');
});
};
// console.log('Entidades onDemand');
}
})();
The view that calls the modal
<section ng-controller="EntidadesEditCtrl as ctrl">
<div class="modal-header">
<h3 class="modal-title">Editando entidade</h3>
</div>
<div class="row">
<div class="modal-body">
<form novalidate class="form-inline">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="fm_name">Email address</label>
<input class="form-control" id="fm_name" ng-model="vm.entidade.name" type="text">
</div>
<div class="form-group">
<label class="sr-only" for="fm_email">Email</label>
<input class="form-control" id="fm_email" ng-model="vm.entidade.email" type="email">
</div>
<div class="form-group">
<label class="sr-only" for="fm_sexo">Sexo</label>
<input class="form-control" id="fm_sexo" ng-model="vm.entidade.gender" type="text">
</div>
<div class="form-group">
<label class="sr-only" for="fm_companhia">Companhia</label>
<input class="form-control" id="fm_companhia" ng-model="vm.entidade.company" type="text">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="fm_id">User ID</label>
<input class="form-control" id="fm_id" ng-model="vm.entidade._id" type="text">
</div>
<div class="form-group">
<label class="sr-only" for="fm_phone">Telefone</label>
<input class="form-control" id="fm_phone" ng-model="vm.entidade.phone" type="tel">
</div>
<div class="form-group">
<label class="sr-only" for="fm_endereco">Endereço</label>
<input class="form-control" id="fm_endereco" ng-model="vm.entidade.address" type="text">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="vm.entidade.isActive">{{vm.entidade.isActive}}
</label>
</div>
</div>
</form>
</div>
</div>
<br>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ctrl.update(vm.entidade); vm.ok()" type="button">OK</button>
<button class="btn btn-warning" ng-click="vm.cancel()" type="button">Cancel</button>
</div>
</section>
and the content to be inserted into body-modal
<div class="row" ng-controller="EntidadesController as ectrl">
<div class="row text-center">
<h1>Gerenciar entidades</h1>
</div>
<hr>
<div class="row col-md-10 col-md-offset-1">
<table class="table table-striped" st-table="rowCollection">
<thead>
<div class="panel ">
<div class="panel-heading">
<button class="btn btn-default pull-right" ng-click="open()">Add</button>
<div class="clearfix"></div>
</div>
</div>
<tr>
<th>#</th>
<th>Nome</th>
<th>Compania</th>
<th>Telefone</th>
<th>email</th>
<th>ação</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="entidade in ectrl.entidades">
<td>{{entidade._id}}</td>
<td>{{entidade.name}}</td>
<td>{{entidade.company}}</td>
<td>{{entidade.phone}}</td>
<td>{{entidade.email}}</td>
<td>
<button class="btn btn-default" ng-click="ectrl.openEditEntidades(entidade)" type="button">
Editar
</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="text-center" colspan="5">
<div st-displayed-pages="7" st-items-by-page="itemsByPage" st-pagination=""></div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
Thanks for u time.
You should use ng-include to insert another template.
<div class="modal" role="dialog" tabindex="-1" data-type="Modal Default">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" data-ng-class="modalOptions.headerClass" ng-show="title">
<button class="close" ng-click="modalOptions.close();" type="button">×</button>
<h4 class="modal-title" ng-bind="modalOptions.headerTitle"></h4>
</div>
<div class="modal-body" ng-include="modalOptions.contentTemplate"></div>
<div class="modal-footer">
<button class="btn btn-default" data-ng-click="modalOptions.close();" data-ng-show="modalOptions.showCloseButton" type="button">
{{modalOptions.closeButtonText}}</button>
<button class="btn btn-primary" data-ng-click="modalOptions.ok();" data-ng-show="modalOptions.showActionButton">
{{modalOptions.actionButtonText}}</button>
</div>
</div>
</div>
</div>

AngularJS - Scope Not Updating

For some reason, I can't remove the description and packing elements/fields (see picture) from the scope variable, even after deleting their respective code and restarting the application. Any help is much appreciated.
My directive:
app.directive('formElement', function() {
return {
restrict: 'E',
transclude: true,
scope: {
label : "#",
model : "="
},
link: function(scope, element, attrs) {
scope.disabled = attrs.hasOwnProperty('disabled');
scope.required = attrs.hasOwnProperty('required');
scope.pattern = attrs.pattern || '.*';
console.log(element);
},
template:
'<div class="form-group">' +
'<label class="col-sm-3 control-label no-padding-right"> {{label}}</label>' +
'<div class="col-sm-7">' +
'<span class="block input-icon input-icon-right" ng-transclude></span>' +
'</div></div>'
};
});
My controllers:
app.controller('ProductsCtrl', function ($scope, $modal, $filter, Data) {
$scope.product = {};
Data.get('products').then(function(data){
$scope.products = data.data;
});
$scope.changeProductStatus = function(product){
product.status = (product.status=="Active" ? "Inactive" : "Active");
Data.put("products/"+product.id,{status:product.status});
};
$scope.deleteProduct = function(product){
if(confirm("Are you sure to remove the product?")){
Data.delete("products/"+product.id).then(function(result){
$scope.products = _.without($scope.products, _.findWhere($scope.products, {id:product.id}));
});
}
};
$scope.open = function (p,size) {
var modalInstance = $modal.open({
templateUrl: 'partials/product-edit.html',
controller: 'ProductEditCtrl',
size: size,
resolve: {
item: function () {
return p;
}
}
});
modalInstance.result.then(function(selectedObject) {
if(selectedObject.save == "insert"){
$scope.products.push(selectedObject);
$scope.products = $filter('orderBy')($scope.products, 'id', 'reverse');
}else if(selectedObject.save == "update"){
p.price = selectedObject.price;
p.stock = selectedObject.stock;
}
});
};
$scope.columns = [
{text:"ID",predicate:"id",sortable:true,dataType:"number"},
{text:"Name",predicate:"name",sortable:true},
{text:"Price",predicate:"price",sortable:true},
{text:"Stock",predicate:"stock",sortable:true},
{text:"Status",predicate:"status",sortable:true},
{text:"Action",predicate:"",sortable:false}
];
});
app.controller('ProductEditCtrl', function ($scope, $modalInstance, item, Data) {
$scope.product = angular.copy(item);
$scope.cancel = function () {
$modalInstance.dismiss('Close');
};
$scope.title = (item.id > 0) ? 'Edit Product' : 'Add Product';
$scope.buttonText = (item.id > 0) ? 'Update Product' : 'Add New Product';
var original = item;
$scope.isClean = function() {
return angular.equals(original, $scope.product);
};
$scope.saveProduct = function (product) {
product.uid = $scope.uid;
if(product.id > 0){
Data.put('products/'+product.id, product).then(function (result) {
if(result.status != 'error'){
var x = angular.copy(product);
x.save = 'update';
$modalInstance.close(x);
}else{
console.log(result);
}
});
}else{
product.status = 'Active';
Data.post('products', product).then(function (result) {
if(result.status != 'error'){
var x = angular.copy(product);
x.save = 'insert';
x.id = result.data;
$modalInstance.close(x);
}else{
console.log(result);
}
});
}
};
});
HTML:
product-edit.html (partial):
<div class="modal-header">
<h3 class="modal-title">Edit product [ID: {{product.id}}]</h3>
</div>
<div class="modal-body">
<form name="product_form" class="form-horizontal" role="form" novalidate>
<form-element label="NAME" mod="product">
<input type="text" class="form-control" name="name" placeholder="Name" ng-model="product.name" ng-disabled="product.id" focus/>
</form-element>
<form-element label="PRICE" mod="product">
<input type="text" name="price" class="form-control" placeholder="PRICE" ng-model="product.price" only-numbers/>
<small class="errorMessage" ng-show="product_form.price.$dirty && product_form.price.$invalid"> Enter the price.</small>
</form-element>
<form-element label="STOCK" mod="product">
<input type="text" name="stock" class="form-control" placeholder="STOCK" ng-model="product.stock" only-numbers/>
<small class="errorMessage" ng-show="product_form.stock.$dirty && product_form.stock.$invalid"> Enter the available stock.</small>
</form-element>
<div class="modal-footer">
<form-element label="">
<div class="text-right">
<a class="btn btn-sm" ng-click="cancel()">Cancel</a>
<button ng-click="saveProduct(product);"
ng-disabled="product_form.$invalid || enableUpdate"
class="btn btn-sm btn-primary"
type="submit">
<i class="ace-icon fa fa-check"></i>{{buttonText}}
</button>
</div>
</form-element>
</div>
</form>
</div>
products.html (partial):
<div class="panel panel-default">
<div class="panel-heading" style="height: 60px;">
<div class="pull-left">
<input placeholder="Filter inventory list ..." class="form-control" aria-describedby="basei" ng-model="filterProduct" ng-change="resetLimit();" autocomplete="off" type="text" focus>
</div>
<div class="pull-right">
<button type="button" class="btn btn-default fa fa-plus" ng-click="open(product);">Add New Product</button>
</div>
</div>
<div class="panel-body">
<div class="input-group pull-right">
</div>
<table class="table table-striped">
<tr ng-show="products.length==0"><td style="vertical-align:middle;"><i class="fa fa-ban fa-3x"></i> No data found</td></tr>
<tr ng-hide="products.length>-1"><td style="vertical-align:middle;"><i class="fa fa-spinner fa-spin"></i> Loading</td></tr>
<tr><th ng-repeat="c in columns">{{c.text}}</th></tr>
<tr ng-repeat="c in products | filter:filterProduct | orderBy:'-id'" id="{{c.id}}" animate-on-change='c.stock + c.price' ng-animate=" 'animate'">
<td>{{c.id}}</td><td>{{c.name}}</td><td>{{c.price}}</td><td>{{c.stock}}</td>
<td>
<button class="btn" ng-class="{Active:'btn-success', Inactive:''}[c.status]" ng-click="changeProductStatus(c);">{{c.status}}</button>
</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default fa fa-edit" ng-click="open(c);"></button>
<button type="button" class="btn btn-danger fa fa-trash-o" ng-click="deleteProduct(c);"></button>
</div>
</td>
</tr>
</table>
</div>
</div>
I often have a problem with my templates being cached while using Angular. In chrome if you have the developer console open you can go to settings and prevent it from using cached results while the console is open. Or clear your browser cache manually

Form Submission in Modal Window and Refresh Content of a Tab

I have 2 tabs: list.brands and add.brand:
<script type="text/ng-template" id="list.brands">
<table class="table table-striped table-bordered bootstrap-datatable datatable dataTable" id="DataTables_Table_0" aria-describedby="DataTables_Table_0_info" ng-controller="BrandsCtrl">
<input type="text" ng-model="searchBox">
<thead>
<tr>
<th><tags:label text="brandid"/></th>
<th><tags:label text="name"/></th>
<th><tags:label text="isactive"/></th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="actionresult{{$index + 1}}" ng-repeat="brand in brands | filter:searchBox">
<td>{{brand.brandid}}</td>
<td>{{brand.name}}</td>
<td>{{brand.isactive}}</td>
<td>
<a class="btn btn-ext-darkblue btn-ext-darkblue savestockbtn" ng-click="open(brand.brandid)"><tags:label text="edit"/></a>
<a class="btn btn-ext-darkblue btn-modal-trigger btn-ext-darkblue savestockbtn" href="/admin.brands/deleteConfirm?brandid={{brand.brandid}}" data-toggle="modal" ><tags:label text="delete"/></a>
</td>
</tr>
</tbody>
</table>
</script>
<script type="text/ng-template" id="add.brand">
<div class="row-fluid sortable">
<div class="box span12">
<div class="box-content">
<form class="form-horizontal" action='/admin.brands/add' data-toggle="modalform" data-popup="modal" name="brandform">
<div class="section-heading"></div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="name"/> *</label>
<div class="controls">
<input name="name" required/>
<span ng-show="brandform.name.$error.required"> Name is required. </span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="isactive"/> </label>
<div class="controls">
<input type="checkbox" name="isactive" value="1">
</div>
</div>
<div class="section-heading"><tags:label text="logo"/></div>
<div class="control-group">
<label class="control-label" for="textarea2"></label>
<div class="controls">
<template:file.upload dropzoneWidth="200px" dropzoneHeight="160px" maxFiles="1"></template:file.upload>
</div>
</div>
<div class="form-actions">
<tags:label text="close"/>
<button ng-disabled="brandform.name.$invalid" type="submit" class="btn btn-ext-lightblue"><tags:label text="save"/></button>
</div>
</form>
</div>
</div>
</div>
</script>
I switch them with
<div class="content-header">
<div class="row">
<div class="content-name span4">
<h3><i class="glyphicon glyphicon-bold"></i><tags:label text="brands"/></h3>
</div>
<div class="span8 button-group">
<jsp:include page="/admin/jsp/screens/help-button-inc.jsp"></jsp:include>
</div>
</div>
</div>
<div ng-app="myApp" ng-controller="TabsCtrl">
<div id="tabs" >
<ul class="nav nav-tabs content-tab-header" id="content_tab_0">
<li ng-repeat="tab in tabs" ng-class="{active:isActiveTab(tab.url)}" ng-click="onClickTab(tab)"><a><i class="{{tab.cssClass}}"></i><tags:label text="{{tab.title}}"/></a></li>
</ul>
</div>
<div id="mainView">
<div ng-include="currentTab"></div>
</div>
At list, I can open a modal window that contains brand details by clicking edit button in list.brands. My modal window:
<div class="row-fluid sortable">
<div class="box span12">
<div class="box-content">
<form class="form-horizontal" name="brandform" action='/admin.brands/update' data-toggle="validate" method="post">
<fields:form formName="brand.id.form">
<input type="hidden" name="brandid" value="{{item.brandid}}"/>
</fields:form>
<fields:form formName="brand.form">
<div class="section-heading"></div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="name"/> *</label>
<div class="controls">
<input name="name" value="{{item.name}}" required/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError"><tags:label text="isactive"/> </label>
<div class="controls">
<input type="checkbox" ng-checked="item.isactive" name="isactive" value="1"/>
</div>
</div>
</fields:form>
<div class="form-actions">
<a ng-click="cancel()" class="btn btn-ext-lightblue"><tags:label text="close"/></a>
<a ng-click="ok()" class="btn btn-ext-darkblue btn-disable-on-submit" ><tags:label text="save"/></a>
</div>
</form>
</div>
</div>
</div>
and my app is here:
<script>
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller("BrandsCtrl", function($scope, $http, $controller) {
$http.get('/admin.brands/getJSONDataOfSearch').
success(function(data, status, headers, config) {
$scope.brands = data;
}).
error(function(data, status, headers, config) {
});
angular.extend(this, $controller("BrandCtrl", {$scope: $scope}));
});
app.controller("BrandCtrl", function ($scope, $http, $modal) {
$scope.animationsEnabled = true;
$scope.open = function (id) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: '/admin.brands/edit',
controller:gg,
resolve: {
item: function($http) {
return $http.get('/admin.brands/getJsonBrandAndEdit?brandid=' + id)
.then(function(response) {
return response.data;
});
}
}
});
}
});
var gg = function ($scope, $modalInstance, item) {
$scope.item = item;
$scope.ok = function () {
$scope.form.brandform.submit();
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss();
};
}
app.controller('TabsCtrl', ['$scope', function ($scope) {
$scope.tabs = [{
title: 'list.brands',
url: 'list.brands',
cssClass: 'icon-th-list'
}, {
title: 'add.brand',
url: 'add.brand',
cssClass: 'icon-plus'
}];
$scope.currentTab = 'list.brands';
$scope.onClickTab = function (tab) {
$scope.currentTab = tab.url;
}
$scope.isActiveTab = function(tabUrl) {
return tabUrl == $scope.currentTab;
}
}]);
</script>
My questions is; how can I submit my edit form in modal to a target URL and refresh the list of brands.
in angular, form has a in-built event called ng-submit. You can submit the form in either way via submit button or using enter key. on ng-submit event, you need to pass a function which must be written within your controller. in that controller you can do what ever you want to do. To use a service, go through the documentation.
Here I am attaching an working example of Form Submit with Service integrated in it (Just for your reference, I have added 2 different controllers which are sharing the same service):
Fiddle: http://jsfiddle.net/ashishanexpert/zvcx5z38/2/
I think this could help you. Thanks
$scope.open = function (id) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: '/admin.brands/edit',
controller:gg,
resolve: {
item: function($http) {
return $http.get('/admin.brands/getJsonBrandAndEdit?brandid=' + id)
.then(function(response) {
return response.data;
});
}
}
});
modalInstance.result.then(function (item) {
//The function that load your data in this controller
LoadData();
})
}

how to call main controllers function from child directive in angularjs

I am not able to call method adddepartment which is in controller.I am calling this method from myCreateDialog.html.
My second directive in under the first directive. I am able to call departments method which is in controller from myDept directive. but not able to call adddepartment method of controller from myCreateDialog directive.
How do i call this method?
myApp.controller('departmentController', ['$scope', 'departmentService' ,
function ($scope, departmentService) {
$scope.departments = departmentService.departments;
var a, b;
//Add New Department
$scope.adddepartment = function (emps) {
departmentService.adddepartment(depts);
$scope.depts = "";
};
}]);
myApp.directive("myDept", function () {
return {
restrict: "E",
scope:{
department:"="
},
templateUrl: 'Template/Alldepartment.html',
replace: false,
transclude:true,
link: function (scope, element, attrs, controller) {}
};
});
myApp.directive("myCreateDialog", function () {
return {
restrict: "E",
scope:{
adddepartment: "&"
},
templateUrl: 'Template/myCreateDialog.html',
link: function (scope, element, attrs, controller) {
}
};
});
App.js
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/Employee', {
templateUrl: 'Template/Employee.html',
controller: 'employeeController'
}).
when('/Department', {
templateUrl: 'Template/Department.html',
controller: 'departmentController'
})
}]);
Department.html
<my-dept department="departments">
<p>This text is coming by transclude</p>
</my-dept>
Alldepartment.html
<div>
<div class='myTransclude' ng-transclude></div>
<button class="btn btn-success" data-toggle="modal" data-target="#crtdept">
<span class="glyphicon glyphicon-plus-sign"></span> Create New Department
</button>
</div><br />
<!--Display department data into table-->
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover ">
<thead>
<tr class="success ">
<th>Id</th>
<th>Name</th>
<th>Technology</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="dept in department">
<td>{{dept.id}}</td>
<td>{{dept.name}}</td>
<td>{{dept.technology}}</td>
<td>
<button class="btn btn-link" title="Edit" data-toggle="modal" data-target="#editemp" ng-click="empedit(employee,employees.indexOf(employee))">
<span class="text-warning glyphicon glyphicon-pencil"></span> Edit 
</button>
<button class="btn btn-link" ng-click="deleteemp(employees.indexOf(employee))">
<span class=" text-danger glyphicon glyphicon-trash "> Delete</span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<!--myCreateDialog directive for showing dialog for creating department-->
<my-create-dialog adddepartment="adddepartment(depts)"></my-create-dialog>
myCreateDialog.html
<div class="modal fade" id="crtdept">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" style="color:red" class=" close" data-dismiss="modal"> ×</button>
<h4 class="modal-title">Create Employee</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" data-toggle="validator" role="form" ng-submit="adddepartment(emps)">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10 has-success">
<input type="text" class="form-control" placeholder="Enter Your Name" ng-model="emps.empnames" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10 has-success">
<input type="email" class="form-control" id="email" placeholder="Enter Your email" ng-model="emps.empemails" required>
</div>
</div>
<div class=" form-group">
<label class="control-label col-sm-2">City:</label>
<div class="col-sm-10 has-success">
<input type="text" class="form-control" placeholder="Enter Your City" ng-model="emps.empcitys" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Department:</label>
<div class="col-sm-10 has-success">
<input type="text" class="form-control" placeholder="Enter your Department" ng-model="emps.empdepts" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Technology:</label>
<div class="col-sm-10 has-success">
<input type="text" class="form-control" placeholder="Enter your Technology" ng-model="emps.emptechs" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success"><span class="glyphicon glyphicon glyphicon-ok"></span> Create</button>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal"> Close</button>
</div>
</div>
</div>
</div>
</div>
You can inject your departmentService into your directive and call it from there
myApp.directive("myCreateDialog", function (departmentService) {
return {
restrict: "E",
templateUrl: 'Template/myCreateDialog.html',
link: function (scope, element, attrs, controller) {
scope.adddepartment = function (emps) {
departmentService.adddepartment(depts);
scope.depts = "";
};
}
};
});

Resources