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>
Related
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>
This question already has answers here:
ng-model for `<input type="file"/>` (with directive DEMO)
(13 answers)
Closed 4 years ago.
Guyz i have an issue with my code i don't know why when i tried to get file from <input ng-model="form.userfile" id="itemImage" name="userfile" type="file">
that code will not give me the values.
my code:
HTML:
<div class="panel panel-default">
<div class="panel-body">
<form id="form" accept-charset="utf-8" ng-submit="sendmessage()">
<textarea ng-model="form.message" name="message"
onkeypress="process(event, this)"
id="text" class="form-control send-message" rows="3"
placeholder="Write a reply...">
</textarea>
</div>
<span class="col-lg-3 btn btn-file send-message-btn">
<i class="glyphicon glyphicon-paperclip"></i>Add Files
<input ng-model="form.userfile" id="itemImage"
name="userfile" type="file">
</span>
<button ng-click="sendmessage()" id="send"
class="col-lg-4 text-right btn send-message-btn pull-right"
type="button" role="button">
<i class="fa fa-plus"></i> Send Message
</button>
<div id="dvPreview" class="text-center"></div>
</form>
</div>
Angular:
$scope.sendmessage = function (){
var formData = $scope.form;
var friendid = $scope.friendid;
var req =
{
type: 'POST',
enctype: 'multipart/form-data',
data:formData,
url: "<?php echo base_url() ?>User/sendmessages/"+friendid,
headers: {
'Content-Type': 'application/json'
},
};
$http(req).then(function (response) {
$('#text').val('');
console.log(response)
}, function (response) {
});
};
here is what i have done before please help.
ngModel directive is not usable on file input.
If you don't care about being in debugInfoEnabled on prod, you can pass it true like this in your app.js.
$compileProvider.debugInfoEnabled(true);
You then will be able to access your scope from your html.
In you file input just add :
onchange="angular.element(this).scope().yourChangeFunction(this)
You can access your file in your js code with :
scope.yourChangeFunction = function(element){scope.file=element.files[0];}
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);
I'm here because i am not being able to make my controller see my html variables our functions, maybe you guys see something i dont =(
HTML:
<article ng-controller="CreateUserController">
<div class="well">
<center>
<h1>Registrar</h1> <button ng-click="test()">Teste</button>
</br>
<form name="form">
<div class="form-group has-feedback"
ng-class="{
'has-error': form.name.$invalid && form.name.$dirty,
'has-success': form.name.$valid && form.name.$touched
}">
<div>
<input ng-disabled="true" type="name" required name="name" class="form-control" placeholder="Nome" ng-model="user.name">
<p class="help-block" ng-messages="form.name.$error">
<span ng-message="required">Nome esta vazio.</span>
</p>
</div>
</div>
</form>
</center>
</div>
</article>
JS:
angular.module('auth').controller('CreateUserController', [
'$scope', '$http', '$location','$state','$routeParams', '$modal','$rootScope',"$resource","Auth",'UserCompaniesService',
function($scope, $http, $location,$state,$routeParams, $modal,$rootScope,$resource,Auth,UserCompaniesService){
$scope.signedIn = Auth.isAuthenticated;
$scope.logout = Auth.logout;
var Account = $resource('/accounts/'+$routeParams.id+'.json',
{},
{ "show": { "method": "GET" }});
account = Account.get({"account_id":$routeParams.id});
//Not being seen
$scope.test = function() {
alert('teste');
}
$scope.user.name = account.name;//$scope.user is not being seen
$scope.user.email = account.email;
user.html.erb
<article ng-app="auth">
<div ng-view></div>
</article>
Can you guys please help me?
It looks like you want to have an object called user on the $scope:
$scope.user.
You have values tied to this object in the model. You have to create this object yourself in your controller's constructor:
$scope.user = {};
Then your model bindings will populate things like
$scope.user.name on it from the input in the HTML.
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>