Update textfield value with ajax data using angular js - javascript

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();
});

Related

pulling user input from modal form (angular)

I currently have a modal form setup and working nicely how i want it but now i need to grab the information inputed into textboxes and selections by the user and im sort of lost as to where i need to start. below is the code for my modal form in entirity. I'm not necessarily looking for a direct answer but to be pointed in the right direction of more information though examples would be greatly appreciated.
<div ng-app='plunker' ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>Create a new post</h3>
</div>
<form name="modalForm">
<div class="modal-body">
<div class="form-group" ng-class="{ 'has-error': modalForm.modalInput.$invalid }" >
<input name="modalInput" type="text" class="form-control" size="10" ng-model="data.myNumber" placeholder="Post Title" required/><br>
<textarea name="modalInput" class="form-control" rows="10" maxlength="1000" form="modalForm" ng-model="data.myNumber2" placeholder="Post Body" required></textarea><br>
<label for="sel1">Select category:</label>
<select name="modalInput" class="form-control" ng-model="data.myNumber3" id="sel1" required>
<option value="" selected disabled>Please select</option>
<option value='lifestyle'>lifestyle</option>
<option value='travel'>travel</option>
<option value='video'>video</option>
</select><br>
<input name="modalInput" type="url" class="form-control" size="10" ng-model="data.myNumber4" placeholder="http://www.postUrlHere.com"/>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-disabled="modalForm.$invalid" ng-class="{ 'disabled': modalForm.$invalid }" ng-click="ok()">Submit</button>
<button class="btn btn-primary" ng-click="cancel()">Cancel</button>
</div>
</form>
</script>
<h1>GWAT Websites and Designs</h1>
<button class="btn" ng-click="open()">Submit new post</button>
</div>
<script>
var myMod = angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function($scope, $uibModal, $log) {
$scope.items = ['title', 'body', 'category', 'url'];
$scope.open = function() {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.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());
});
};
};
edit:
var ModalInstanceCtrl = function($scope, $uibModalInstance, data) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function() {
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
};
myMod.controller('ModalDemoCtrl', ModalDemoCtrl);
myMod.controller('ModalInstanceCtrl', ModalInstanceCtrl);
</script>
If you are looking to send the $scope.data from the current page to a modalInstance, you will have to add a property to the resolve object.
$scope.open = function() {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
data: function() {
return $scope.data;
}
}
});
From the ModalInstanceCtrl, add "data" as a dependency, and you will be able to retrieve the relevant data.

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

Unable to append rendered text in angular JS

My controller:
myApp.controller('actionEditController', ['$scope', '$stateParams', '$sce',function ($scope, $stateParams, $sce) {
$context = $scope;
$.get(apiHost + "/action/entity/" + $stateParams.id)
.success(function (response) {
angular.module('broConsoleApp', ['ngSanitize']);
var action = response['RESPONSE'];
action.params = JSON.parse(action.paramsJson);
console.log(action);
var table = $.hbs("/templates/action.hbs", action);
var el=angular.element(table);
$scope.content= $sce.trustAsHtml(table);
console.log(table);
})
.error(function (jqXHR, textStatus, errorThrown) {
console.error("Error retrieving action", textStatus, errorThrown);
});
}])
;
My .hbs :
<div>
<input name="name" type="text" value="{{name}}"/>
<input name="id" type="text" readonly="readonly" value="{{id}}"/>
<input name="type" type="text" readonly="readonly" value="{{actionType}}"/>
</div>
My .html file :
<div ng-app="myApp" ng-controller="actionEditController" >
<h2 class="marcellus text-center"> EDIT ACTION </h2>
<div ng-bind-html="content">
</div>
</div>
I am getting the rendered data in table from
$.hbs
.However the ng-bind-html does not seem to be appending / binding this value to the HTML . The final output is only
EDIT ACTION
The rendered data does not display.

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

Getting data from modal AngularJS

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.

Categories

Resources