I have problem with input fields in AngularJS. Whatever I write in one, I getting exactly same text in another one (field_start = field_end). What am I doing wrong? Is it something wrong with ng-model?
template.html
<form name="editForm" role="form" novalidate ng-submit="vm.save()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"
ng-click="vm.clear()">×</button>
<h4 class="modal-title" id="myPackLabel">Create offer</h4>
</div>
<div class="modal-body">
<jhi-alert-error></jhi-alert-error>
<div class="form-group">
<label class="control-label" for="field_start">Miejsce startowe</label>
<input type="text" class="form-control" name="field_start" id="field_start"
ng-model="vm.transitPointStart.city" placeholder="np. Warszawa"
/>
</div>
<div class="form-group">
<label class="control-label" for="field_end">Miejsce docelowe</label>
<input type="text" class="form-control" name="field_end" id="field_end"
ng-model="vm.transitPointEnd.city" placeholder="np. Wrocław"
/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
<span class="glyphicon glyphicon-ban-circle"></span> <span>Cancel</span>
</button>
<button type="submit" ng-disabled="editForm.$invalid || isSaving" class="btn btn-primary">
<span class="glyphicon glyphicon-save"></span> <span>Save</span>
</button>
</div>
</form>
controller.js
(function() {
'use strict';
angular
.module('myApp')
.controller('AddOfferDialogController', AddOfferDialogController);
AddOfferDialogController.$inject = ['$scope', '$stateParams', '$uibModalInstance', 'entity', 'ShipmentOffer', 'TransitPoint', 'PackageSlot'];
function AddOfferDialogController ($scope, $stateParams, $uibModalInstance, entity, ShipmentOffer, TransitPoint) {
var vm = this;
vm.shipmentOffer = entity;
vm.transitPointStart = entity;
vm.transitPointEnd = entity;
vm.save = function () {
vm.shipmentOffer.date = new Date();
TransitPoint.save(vm.transitPointStart);
TransitPoint.save(vm.transitPointEnd);
ShipmentOffer.save(vm.shipmentOffer);
$uibModalInstance.close();
vm.isSaving = false;
}
vm.clear = function() {
$uibModalInstance.dismiss('cancel');
};
}
})();
You are using the same object in your two references:
vm.transitPointStart = entity;
vm.transitPointEnd = entity;
maybe you need to create a clone to have different objects in your references (it depends of your requirements):
vm.transitPointStart = Object.assign({}, entity);
vm.transitPointEnd = Object.assign({}, entity);
Related
I'm working on an MVC project. My requirement is to insert data to the database through a form. I've included the form inside a bootstrap modal.
My problem is, when I enter some data and click the save button, it inserts only null rows, not the entered values. Why does this happen? How do I make it to insert the real values instead of just passing nulls?
Here's the code for the modal.
#if (Model != null)
{
<div class="modal-content">
<!--modal header-->
<div class="modal-body">
<form id="actionForm">
<div class="form-group">
<label>Name</label>
<input type="text" name="Name" class="form-control" placeholder="Enter Accomodation Type Name...">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="Description" class="form-control" placeholder="Enter Accomodation Type Description..."></textarea>
</div>
</form>
<div id="errorDiv">
</div>
</div>
<div class="modal-footer">
<button type="button" id="actionButton" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
}
This is the script for the Save Changes button
<script>
$("#actionButton").click(function () {
$.ajax({
url: '#Url.Action("Action", "AccomodationTypes")',
type: "post",
data: $("actionForm").serialize()
})
.done(function (response) {
debugger;
if (response.Success) {
location.reload();
}
else {
$(".errorDiv").html(response.Message)
}
});
});
</script>
Since you are using $("actionForm").serialize() you have to bind the model to the form input controls:
<input type="text" asp-for"#Model.Name" name="Name" class="form-control"
placeholder="Enter Accomodation Type Name...">
// or you can try to replace asp-for by value="#model.Name"
<textarea asp-for="#Model.Description" name="Description" class="form-control"
placeholder="Enter Accomodation Type Description..."></textarea>
or if you using older versions of MVC you can try replace your input controls with this:
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
#Html.TextAreaFor(m => m.Description, new { #class = "form-control" })
And you have an javascript bug too. Replace
$("actionForm").serialize()
with
$("#actionForm").serialize()
or even better:
$("#actionForm").serializeArray()
I'm starting my steps with AngularJS.
He builds a small application in conjunction with CodeIgniter 3.
I created CRUD and everything works fine.
However, I would like to add a textarea in which I will add a lot of information in the format:
link1.com
link2.com
link3.com
The data will go to the database and will be saved as unique records.
My AngularJS - code:
$scope.noteCreated = function( note ){
$http({
method: 'POST', url: 'api/admin/notes/create/', data: {'note' : note}}
).then(function (){
$scope.success = true;
$timeout( function(){
$scope.success = false;
$scope.note = {};
}, 2000);
},function (error){
console.log('Error');
});
}
My html Code:
<form ng-submit="noteCreated(note)">
<div class="container">
<div class="row">
<div class="col-lg-12">
<label>Note</label>
<div text-angular="text-angular" ng-model="note.noted" required></div>
<select ng-model="note.id_domain_rel" chosen="directiveOptions" ng-options="item.id as item.domain_name for item in domain track by item.id" required><option value=""></option>
</select>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" ng-if="!success">Save</button>
<button type="button" class="btn btn-success" ng-if="success" disabled>Saved</button>
</form>
I'm using ng-switch to switch between two functionalities on my webapp, downloading and uploading (controlled by two buttons). When the user wants to download, I use a textbox and submit button to pass the search query to an $http POST request in my js file.
This is the HTML code:
<button class="btn" name="search" ng-click="name = 'download'">Search & Download</button>
<button class="btn" name="upload" ng-click="name = 'upload'">Upload & Index</button>
<div ng-switch="name">
<div ng-switch-when="download">
<input type="text" ng-model="docsterm" my-enter="postData()" placeholder="Search">
<br><br>
<uib-accordion close-others="oneAtATime">
<div uib-accordion-group class="panel-default" heading={{result._source.filename}} ng-repeat="result in results.data.hits.hits">
<span ng-bind-html="highlight(result._source.attachment.content, docsterm)"></span>
<br><br>
<button class="btn">Preview</button>
<!-- Create the download button -->
<button class="btn" ng-click="download(result._source.data, result._source.filename, result._source.attachment.content_type)"><i class="fa fa-download"></i>
<!-- <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a> -->
<br>
<!--
<ul uib-pagination boundary-links="true" total-items="results['hits']['total']" ng-model="currentPage" items-per-page="5" class="pagination-sm" previous-text="‹" next-text="›" first-text="«" last-text="»"></ul>
-->
</div>
</uib-accordion>
</div>
<div ng-switch-when="upload">
<!-- Multiple files -->
<button class="btn" ngf-select ng-model="files" ngf-multiple="true">Select Files</button>
<button class="btn" ng-click="submit()">Submit</button>
</div>
</div>
This is my js code:
docsApp.controller('docsController', function ($scope, $http, $sce) {
$scope.docsterm = "";
$scope.results = "";
$scope.currentPage = 1;
$scope.content = "";
$scope.content_type = "";
$scope.postData = function(docsterm) {
$http({
url: 'http://192.168.100.30:9200/my_index4/_search?q=' + $scope.docsterm,
method: "POST"
})
.then(function(response) {
$scope.results = response;
// $scope.content_type = response.data.
console.log($scope.results);
/*console.log($scope.content);
console.log($scope.content_type);*/
},
function(response) { // optional
$scope.results = "No results found."
});
}
However, docsterm is not being passed through to the js file.
In the console, I can see the $http request being sent is:
http://192.168.100.30:9200/my_index4/_search?q=
It should be:
http://192.168.100.30:9200/my_index4/_search?q=whateverDocstermIs
Of note, the exact download function code works fine when it is not nested inside the ng-switch, which leads me to believe that ng-switch is causing some issues.
Any ideas? Thanks!
My guess, it's because ng-switch behaves like ng-if - it creates its own scope.
To reach the scope of the controller you need to have $parent. before the model
<input type="text" ng-model="$parent.docsterm" my-enter="postData()" placeholder="Search">
Here is an example of this (with and without $parent)
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "download"
$scope.foo = function() {
console.log("Works:", $scope.docsterm);
console.log("Doesn't work:", $scope.docsterm2);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-switch="name">
<div ng-switch-when="download">
<input type="text" ng-model="$parent.docsterm">
<input type="text" ng-model="docsterm2">
<button ng-click="foo()">Click</button>
</div>
<div ng-switch-when="upload">
...
</div>
</div>
</div>
</body>
</html>
I'm trying to input a username and password into the input fields and send them to the API URL to authenticate the user and return data. I can provide hardcoded credentials to the URL and successfully login. But what I need is to able to input values in the Web interface dynamically and perform the login.
I have no idea how to bind input values into the URL and how the format should be written. Please help with this.
My controller with hard-coded username and password:
var login = angular.module('login', []);
login.controller('loginController', ['$scope','$http','$location',function($scope, $http) {
$scope.loginauth = function(username,password)
{
$http({
method : 'POST',
url : 'http://televisionarybackendservices.azurewebsites.net/auth/login?username=Evangeli&password=1234',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data)
$scope.userData = data;
});
};
enter code here}]);
My html modal to log in;
<div id="loginModal" class="modal fade" role="dialog" ng-controller="loginController">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<form class="form" action="" method="POST" enctype="multipart/form-data" role="form">
<div class="form-group">
<label for="ue">Username</label>
<input type="text" class="form-control" id="ue" placeholder="" ng-model="username">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" class="form-control" id="pwd" placeholder="" ng-model="password">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" ng-click="loginauth(username,password)">Login</button>
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
<div ng-repeat="data in userData">
{{data.username}}<br />
{{data.created_at}}
</div>
</div>
</div>
</div>
I need to enter username and password dynamically and not supply hard-coded values. Thanks in advance.
Well i got the answer.This is for anyone who need help.
var login = angular.module('login', []);
login.controller('loginController', ['$scope','$http','$location',function($scope, $http) {
$scope.loginauth = function(username,password)
{
$http({
method : 'POST',
url : 'http://televisionarybackendservices.azurewebsites.net/auth/login',
data: jQuery.param({
username: $scope.username,
password: $scope.password
}),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data)
$scope.userData = data;
});
};
}]);
I'm relatively new to angular and i'm trying to bind my form radio buttons so I can post the data to the back end.
My problem is when I try to submit the form, the variable formData doesn't contain any of the information entered in the form. I tried binding outside of the ng-repeat on a simple text input and it worked.
Here is my HTML
<section ng-app="IrsTestFactor">
<div ng-controller="IrsController as IrsCtrl">
<h2>
The IRS 20-Factor Test
<span id="loading" ng-show="isProcessing">
<span>
-
<img src="#Url.Content("~/Content/img/ajax-loader.gif")" alt="loading..." />
Processing please wait
</span>
</span>
</h2>
<section class="content-indent">
<p ng-show="emptyModel">Error - model is empty </p>
<form ng-submit="processForm()" ng-hide="IRSCtrl.emptyModel">
<br />
<div ng-class="alertClass" class="alert" role="alert" id="alert" ng-show="alert">
{{alertMessage}}
</div>
<br />
<div class="jumbotron well well-lg">
<p>
Please answer the questions below. The IRS developed this 20-Factor test to determine if a business controls and directs a worker, or has a right to do so. The factors (questions), applied to
each individual circumstance under which services are to be performed, determine the individual's classification. The questions must be objectively and consistently applied in order to determine the
individual's correct status. If the predominance of answers to the 20 questions is "yes", the individual is most likely an employee. If the predominance of answers is "no", the individual is most
likely an independent contractor.
</p>
</div>
<br /><br />
<div ng-repeat="question in questionnaire">
<div class="btn-group col-xs-offset-1 col-xs-2 col-sm-2" data-toggle="buttons">
<span class="btn btn-primary">
<input type="radio" name="item_{{$index}}" ng-model="$parent.formData" value="false"> No
</span>
<span class="btn btn-primary">
<input type="radio" name="item_{{$index}}" ng-model="$parent.formData" value="true"> Yes
</span>
</div>
<span class="message col-xs-8 col-sm-8">{{question.QuestionPhrase}}</span>
<br /><br /><br />
</div>
<input type="text" ng-model="formData.word" name="word" />
<div class="centered-panel-btn">
<a type="button" href="/#ContractManagerConfig.RootUrl()/Home/" class="btn btn-default">
<span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span>
Cancel
</a>
<button type="submit" class="profile-savenext btn btn-success" value="next">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
Submit
</button>
</div>
</form>
</section>
</div>
and here is my angular:
var app = angular.module('IrsTestFactor', []);
app.controller('IrsController', function ($scope, $http) {
$scope.isProcessing = false;
$scope.alert = false;
$scope.alertClass = "";
$scope.alertMessage = "";
$scope.formData = {};
$scope.emptyModel = false;
/** Http request to get all questions for the irs questionnaire [caching] */
$http({
method : 'GET',
cache : true,
url : 'GetQuestionnaire'
}).success(function (data) {
$scope.questionnaire = data.QuestionnaireList;
$scope.emptyModel = false;
}).error(function () {
alert("error");
$scope.emptyModel = true;
});
$scope.processForm = function () {
$scope.isProcessing = true;
formData = JSON.stringify($scope.formData);
alert(formData);
$http({
method : 'POST',
url : 'SaveIRSFactorTest',
data : $scope.formData, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
$scope.alert = false;
$('html, body').animate({ scrollTop: 0 }, 'slow');
if (!data.success) {
$scope.alertClass = "alert-danger";
$scope.alertMessage = data.message;
$scope.isProcessing = false;
$scope.alert = true;
} else {
//success
$scope.alertClass = "alert-success";
$scope.alertMessage = data.message;
$scope.alert = true;
}
$scope.alert = true;
})
.error(function (data) {
$scope.alert = false;
$('html, body').animate({ scrollTop: 0 }, 'slow');
$scope.alertClass = "alert-danger";
$scope.alertMessage = data.message;
$scope.isProcessing = false;
$scope.alert = true;
});
}
});
ng-model should be a property from the scope. Setting it to an empty object $parent.formData will not work. Moreover you have the radio buttons inside ng-repeat so you have to generates the model based on the item index. Try something like this.
<div ng-repeat="question in questionnaire">
<div class="btn-group col-xs-offset-1 col-xs-2 col-sm-2" data-toggle="buttons">
<span class="btn btn-primary">
<input type="radio" name="item_{{$index}}" ng-model="formData['item_' + $index]" value="false"> No
</span>
<span class="btn btn-primary">
<input type="radio" name="item_{{$index}}" ng-model="formData['item_' + $index]" value="true"> Yes
</span>
</div>
<span class="message col-xs-8 col-sm-8">{{question.QuestionPhrase}}</span>
<br /><br /><br />
</div>
So it turns out that the problem was coming from the spans. I changed them to labels and it worked.
Here is the code:
<div ng-repeat="question in questionnaire">
<div class="btn-group col-xs-offset-1 col-xs-2 col-sm-2" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="question{{$index}}" ng-model="formData[$index]" value="false"> No
</label>
<label class="btn btn-primary">
<input type="radio" name="question{{$index}}" ng-model="formData[$index]" value="true"> Yes
</label>
</div>
{{formData}}
<span ng-bind="question.QuestionPhrase" class="message col-xs-8 col-sm-8"></span>
<br /><br /><br />
</div>