Getting data from modal AngularJS - javascript

I am trying to get data FROM modal to invoking controller, and all the examples I have found only describe way to get data to modal.
What is the proper way to do it?
This is a form I am using in modal:
<form class="form-horizontal">
<div class="modal-body">
<div class="control-group">
<label class="control-label">Name:</label>
<div class="controls">
<input type="text" ng-model="transaction.name" placeholder="Transaction name" />
</div>
</div>
<div class="control-group">
<label class="control-label">Category</label>
<div class="controls">
<input type="text" ng-model="transaction.category" placeholder="Category" />
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<input type="text" ng-model="transaction.amount" placeholder="Amount" />
</div>
</div>
<div class="control-group">
<label class="control-label">Date</label>
<div class="controls">
<input type="text" datepicker-popup="dd-MMMM-yyyy" ng-model="transaction.date" is-open="opened" min="minDate" max="'2015-06-22'" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" />
<button class="btn" ng-click="open()"><i class="icon-calendar"></i></button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn pull-left" data-dismiss="modal">
<i class="icon-remove"></i> Cancel
</button>
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction()">
<i class="icon-ok icon-white"></i> Save Changes
</button>
</div>
These are controllers:
moneyApp.controller("TransactionController", function($scope, $http, $modal, $log) {
console.log("modal: ", $modal);
$scope.transaction = {}
$scope.open = function() {
var modalInstance = $modal.open({
templateUrl: 'partials/modal.html',
controller: 'ModalInstanceController',
resolve: {
transaction: function() {
return $scope.transaction;
}
}
});
modalInstance.result.then(function (receivedTransaction) {
$scope.selected = receivedTransaction;
console.log("Transaction received: ", transaction);
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$http({method: 'GET', url: 'transactions/15/all/'}).success(function(data) {
$scope.transactions = data; // response data
});
})
and
moneyApp.controller("ModalInstanceController", function($scope, $modalInstance, $http, transaction) {
$scope.createTransaction = function() {
console.log("Transakcja: ", $scope.transaction);
$scope.transaction.budgetId = 15;
$scope.selected = {
item: $scope.transaction
}
$http({method: 'POST', url: 'transactions/add/', data : $scope.transaction, headers:{'Accept': 'application/json', 'Content-Type': 'application/json; ; charset=UTF-8'}}).success(function(data) {
console.log("Transaction succesfully added to a DB...");
});
}
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
When I am trying to invoke method createTransaction, $scope.transaction is undefined. How to get data from this form?

I think you need to assign transaction to $scope.transaction in your ModalInstanceController because you are passing in the transaction object but not putting it into $scope.
$scope.transaction = transaction

In your Modal form you need to pass the ng-model object(ie transaction) to the function (createTransaction()) which gets called on form submit.
<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction(transaction)">
<i class="icon-ok icon-white"></i> Save Changes
</button>
And in your controller add the object as parameter to the java-script function.
$scope.createTransaction = function(transaction) {
console.log("transaction details: "+ transaction.category+" "+transaction.amount);
};
Let me know if you are facing any issues, i can share the working code of mine.

Related

How to use multiple ng-app and add new modal

Here is my todo.js file
//let example = angular.module("example", ["ngStorage"]);
example.controller("ExampleController", function($scope, $localStorage) {
$scope.save = function() {
let testObject = [
{
name:"aaa",
lastName:"bbb"
},
{
name:"ccc",
lastName:"ddd"
}
]
let myVal = $localStorage.myKey;
$localStorage.$reset();
if(!myVal){
console.log("okey");
$localStorage.myKey = testObject;
} else {
myVal.push({
name:"fff",
lastName:"ggg"
})
$localStorage.myKey = myVal;
}
$scope.datas = $localStorage.myKey;
}
$scope.load = function() {
console.log($localStorage.myKey)
}
});*/
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", function ($scope, $modal, $log) {
$scope.showForm = function () {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function () {
return $scope.userForm;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, userForm) {
$scope.form = {}
$scope.submitForm = function () {
if ($scope.form.userForm.$valid) {
console.log('user form is in scope');
$modalInstance.close('closed');
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
And here is my index.html file:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="../node_modules/angular-1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.min.js"></script>
<script src="./todo.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
</head>
<body>
<!--<div ng-app="example">
<div ng-controller="ExampleController">
<button ng-click="save()">Save</button>
<button ng-click="load()">Load</button>
<br>
<input type='text' ng-model='searchText' placeholder="Search..." />
<ul>
<li ng-repeat="data in datas | filter:searchText">
{{data.name}}
</li>
</ul>
</div>
</div>-->
<div ng-app="modalFormApp">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<div ng-controller="modalAccountFormController">
<div class="page-body">
<button class="btn btn-primary" ng-click="showForm()">Create Account</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Lastly here is my modal.html:
<div class="modal-header">
<h3>Create A New Account!</h3>
</div>
<form name="form.userForm" ng-submit="submitForm()" novalidate>
<div class="modal-body">
<!-- NAME -->
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="name" required>
<p ng-show="form.userForm.name.$invalid && !form.userForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<!-- USERNAME -->
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
<p ng-show="form.userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="form.userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div>
<!-- EMAIL -->
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="email" required>
<p ng-show="form.userForm.email.$invalid && !form.userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="form.userForm.$invalid">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</form>
I'm trying to open a modal when i click the button. I made comment line the other part which i'm using but it works fine. The second part is for only the modal but it is not working. I even can not open the modal. If there is a basic way to do this can you share with me? I only need to open this modal. I can handle the rest of it.
From the Docs:
There are a few things to keep in mind when using ngApp:
only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.
For more information, see
AngularJS ng-app Directive API Reference

AngularJS unable to recognise function

I'm experiencing a similar problem as
The $scope variable is undefined unless I forced it to retrieve from service again
I'm getting the below error from angular js when i'm trying to invoke a function from a service
TypeError: $scope.watchlist.addStock is not a function
This is my below controller
angular.module('stockDogApp')
.controller('WatchlistCtrl', function ($scope,$routeParams,$modal,WatchlistService,CompanyService) {
$scope.companies = CompanyService.query();
$scope.watchlist = WatchlistService.query($routeParams.listId);
console.log($scope.watchlist);
$scope.stocks = $scope.watchlist.stocks;
$scope.newStock = {};
var addStockModal = $modal({
scope : $scope,
templateUrl : 'views/templates/addstock-modal.html',
show: false
});
$scope.showStockModal = function(){
addStockModal.$promise.then(addStockModal.show);
};
$scope.addStock = function(){
$scope.watchlist.addStock({
listId : $routeParams.listId,
company: $scope.newStock.company,
shares: $scope.newStock.shares
});
addStockModal.hide();
$scope.newStock = {};
};
When i log $scope.watchlist - the function does seem to be present in the object
Object {name: "Saklep", description: "Saklep", id: 0, stocks: Array[0]}
addStock: function(stock)
arguments: (...)
caller: (...)
length: 1
name: ""
This is the html for the modal window
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="$hide()">×</button>
<h4 class="modal-title">Add New Stock</h4>
</div>
<form role="form" id="add-stock" name="stockForm">
<div class="modal-body">
<div class="form-group">
<label for="stock-symbol">Symbol</label>
<input type="text"
class="form-control"
id="stock-symbol"
placeholder="Stock Symbol"
ng-model="newStock.company"
bs-options="company as company.label for company in companies"
bs-typeahead
required>
</div>
<div class="form-group">
<label for="stock-shares">Shares Owned</label>
<input type="number"
class="form-control"
id="stock-shares"
placeholder="# Shares Owned"
ng-model="newStock.shares"
required>
</div>
</div>
<div class="modal-footer">
<button type="submit"
class="btn btn-success"
ng-click="addStock()"
ng-disabled="!stockForm.$valid">Add</button>
<button type="button"
class="btn btn-danger"
ng-click="$hide()">Cancel</button>
</div>
</form>
</div>
</div>
</div>
EDIT: Adding the watchlist Service
angular.module('stockDogApp')
.service('WatchlistService', function () {
var loadModel = function(){
var model = {
watchlists : localStorage['StockDog.watchlists'] ? JSON.parse(localStorage['StockDog.watchlists']) : [],
nextId : localStorage['StockDog.nextId'] ? parseInt(localStorage['StockDog.nextId']) : 0
};
_.each(model.watchlists,function(watchlist){
_.extend(watchlist,WatchlistModel);
_.each(watchlist.stocks,function(stock){
_.extend(stock,StockModel);
});
});
return model;
};
var StockModel = {
save: function(){
var watchlist = findById(this.listId);
watchlist.recalculate();
saveModel;
}
};
var WatchlistModel = {
addStock: function(stock){
var existingStock = _.find(this.stocks,function(s){
return s.company.symbol === stock.company.symbol;
});
if (existingStock){
existingStock.shares += stock.shares;
}else{
_.extend(stock,StockModel);
this.stocks.push(stock);
}
this.recalculate();
saveModel();
},
Turns out Angular-Yeoman automatically generates a controllerAs function in app.js and its the reason for the conflict
.when('/watchlist/:listId', {
templateUrl: 'views/watchlist.html',
controller: 'WatchlistCtrl',
// controllerAs: 'watchlist'
})
commenting out controllerAs did the trick

send data from my controller to my ngDialog

In my controller i have this code, i get the id from one table in the html template and get one object from services and return to ngDialog to show to Edit this data and save in my api-rest:
(function() {
'use strict';
angular
.module('app')
.controller('FraseController', FraseController);
FraseController.$inject = ['FraseService','ngDialog'];
function FraseController(FraseService,ngDialog) {
var vm = this;
vm.texto = rpeuba;
vm.iden = 0;
vm.efrase = '';
vm.edit = function(){
FraseService.get().then(function(response){
console.log(response.data.response);
vm.efrase = response.data.response;
ngDialog.open({
template: 'newFrase',
scope: this
});
});
}
}
}());
and in this html code:
<script type="text/ng-template" id="newFrase">
<h1>Nueva Frase {{vm.texto}}</h1>
<div class="modal-body">
<div class="row">
<div class="form-group">
<label for="frase" class= "col-lg-2 espaciar">Frase: </label>
<div class="col-lg-10">
<input ng-model="frase.efrase.frace" type="text" name="frase" id="frase" class="form-control" placeholder="Escriba su frace aquí">
</div>
<br>
<label for="autor" class= "col-lg-2 control-label espaciar">Autor: </label>
<div class="col-lg-10 ">
<input type="text" name="autor" name="autor" class="form-control" placeholder="Escriba el Autor aquí">
</div>
<br>
<label class="col-lg-2 espaciar">Banner: </label>
<div class="col-lg-10">
<select name="banner" class="form-control selectize-input espaciar">
<option value="0"><< Ninguno >></option>
<option ng-repeat="itemb in FraseController.lbanner" value="{{itemb.id}}">
{{itemb.titulo}}
</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-default"
ng-click="closeThisDialog('tiempo')">Cancelar</button>
<input name="submit" value="Insertar" class="btn btn-primary" title="Insertar" type="submit">
</div>
</script>
i want to show data from my controller in my ngDialog to Edit a one Frase
Good morning, here are how to solve all my problems with ngDialog.
as I run for an answer to what I call ngDialog.openConfirm and on the response run my controller methods mother and passed as a parameter an object from which consume your data.
This is my code to delete a frase.
JS in my controller:
vm.drop = function(__frase){ //Drop the frase
ngDialog.openConfirm({
template: '<h3>You are sure to delete the phrase<h3> '+
'<div class="modal-footer"> '+
'<button type="button" '+
'ng-click=closeThisDialog("Cancel") '+
'class="btn btn-default">Cancel'+
'</button> '+
'<button type="button" '+
'ng-click=confirm(dfrase.frase.id) '+
'class="btn btn-primary">Delete</button> '+
'</div>',
plain:true,
controllerAs: 'dfrase',
controller: [function() {
var vm = this;
vm.frase = __frase;
}]
})
.then(
function(value) { //ok
FraseService.drop(value).then(function(response) {
console.log(response.data.response);
});
refresh();
},
function(value) { //cancel
console.log(value);
}
);
}
FraseService consumer that is a factor with which it interacted with my api and refresh method refreshes me the frase list items.
D greetings

Why my form action in modal is not update?

I am working with modal form in AngularJs. I have to send different request according to what was entered in the form. I want to change the action url of the form. I want to have a calculate url. When i open the modal my url is not updated in the form action. Why ? What is wrong ?
Here is the code
<script>
angular.module('plunker', ['ui.bootstrap']);
var url = '/url/test'; // this value is calculated
var ModalDemoCtrl = function ($scope, $modal, $log) {
/* Note: The hard coded user object has been commented out, as
it is now passed as an object parameter from the HTML template.
*/
/* $scope.user = {
user: 'name',
password: null
};*/
$scope.open = function (user) {
$scope.user = user;
$modal.open({
templateUrl: 'myModalContent.html',
backdrop: true,
windowClass: 'modal',
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = user;
$scope.submit = function () {
$log.log('Submiting user info.');
$log.log(JSON.stringify(user));
$modalInstance.dismiss('cancel');
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
user: function () {
return $scope.user;
}
}
});
};
};
</script>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<!--HERE I WANT TO CHANGE THE ACTION URL ACCORDING TO THE USER -->
<form action="{{'/app/'+url}}" ng-submit="submit()">
<div class="modal-body">
<label>User name</label>
<input type="text" ng-model="user.user" />
<label>Password</label>
<input type="password" ng-model="user.password" />
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<input type="submit" class="btn primary-btn" value="Submit" />
</div>
</form>
</script>
<button class="btn" ng-click="open({user: 'username', password: 'password'})">Open me!</button>
<div ng-show="user.password">Got back from modal: {{ user | json}}</div>
</div>
Here is a plunker ( Line 57)
Thanks
You don't have defined your 'url' in modelDemoCtrl
please see working demo here http://plnkr.co/edit/Ddb13hqqrrdCdA5SuRyS?p=preview
TEMPLATE:
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
<p>Your Url: <strong>{{url.user}}</strong></p>
</div>
<!--HERE I WANT TO CHANGE THE ACTION URL ACCORDING TO THE USER -->
<form action="{{'/app/'+url.user}}" ng-submit="submit()">
<div class="modal-body">
<label>User name</label>
<input type="text" ng-model="user.user" />
<label>Password</label>
<input type="password" ng-model="user.password" />
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
<input type="submit" class="btn primary-btn" value="Submit" />
</div>
</form>
</script>
JS:
$scope.open = function (user) {
$scope.user = user;
$modal.open({
templateUrl: 'myModalContent.html',
backdrop: true,
windowClass: 'modal',
controller: function ($scope, $modalInstance, $log, user) {
$scope.user = user;
$scope.url = $scope.user;
$scope.submit = function () {
$log.log('Submiting user info.');
$log.log(JSON.stringify(user));
$modalInstance.dismiss('cancel');
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
user: function () {
return $scope.user;
}
}
});
};

Update textfield value with ajax data using angular js

I am using angular js directives for bootstrap. What i am trying for is to create an edit form on bootstrap modal when user clicks on edit button from list of items. Here is my code:
HTML:
<div class="modal-header">
<h3>Edit Template</h3>
</div>
<div class="modal-body">
<form name="form" class="form-horizontal" novalidate>
<fieldset>
<div class="span4" ng-class="smClass" ng-show="etemplate.status">{{etemplate.status}}</div>
<div class="control-group">
<label class="control-label" for="etemplateName">Name</label>
<div class="controls">
<input class="input-xlarge" id="etemplateName" ng-model="eTemplate.name" maxlength="150" type="text" required />
</div>
</div>
<div class="control-group">
<label class="control-label" for="etemplateDesc">Description</label>
<div class="controls">
<textarea id="templateDesc" id="etemplateDesc" ng-model="eTemplate.desc"></textarea>
</div>
</div>
<div class="center">
<input type="text" style="display:none;" ng-model="eTemplate.id" value="{{eTemplate.id}}" required />
<button type="button" ng-click="update(eTemplate)" class="btn btn-primary" ng-disabled="form.$invalid || isUnchanged(eTemplate)">Submit</button>
<button class="btn" ng-click="cancel()">Cancel</button>
</div>
</fieldset>
</form>
</div>
Controller:
controller('TemplateController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
var tmpId = '';
$scope.openEdit = function(id) {
tmpId = id;
var editTmpModalInstance = $modal.open({
templateUrl: 'editTemplateContent.html',
controller: 'ETModalInstance'
});
$http({
method: 'GET',
url: adminBaseUrl+'/get_template/',
params: {'id': tmpId}
}).
success(function(data, status, headers, config) {
$scope.$broadcast('EditTemplateDataReached', data);
}).
error(function(data, status, headers, config) {
});
}
}]).
controller('ETModalInstance', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance) {
$scope.emaster = {};
$scope.smClass = '';
$scope.eTemplate = {};
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
$scope.isUnchanged = function(eTemplate) {
return angular.equals(eTemplate, $scope.master);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.update = function(eTemplate) {
var strng = $.param(eTemplate);
};
}]).
My work around for achieving this is when user clicks on edit button id of selected item is passed in my controller which sends an ajax request to server and then fill the fields with respective values. However my fields are not populated when ajax data is returned.
Found the problem in my code i was using $scope for broadcasting and catching the data whereas i have to use $rootScope.
Wrong:
$scope.$broadcast('EditTemplateDataReached', data);
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
Correct:
$rootScope.$broadcast('EditTemplateDataReached', data);
$rootScope.$on('EditTemplateDataReached', function(e, data) {
$scope.eTemplate = data;
$scope.$apply();
});

Categories

Resources