I'm currently working on an AngularJS project and I would like to print option selected on a drop down list together with input data that has been entered by the user without using the backend. How can this be done using AngularJS? Any help?
I believe you wanted something like Prefix + Name, her https://jsfiddle.net/datachand/szc550yb/3/
<div ng-controller="UserCtrl as vm">
<select ng-model="vm.prefix">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
<input type="text" ng-model="vm.name" placeholder="Enter your Name">
<button ng-click="vm.submit()">
Send
</button>
</div>
A controller is needed at any case, even if it's empty:
angular.module('app', []);
function UserCtrl ($log) {
$log.log('UserCtrl');
var vm = this;
vm.submit = function () {
$log.log(vm.prefix, vm.name);
$window.location.href = "https://towhateverurl" + "?prefix=" + vm.prefix +"&name=" + vm.name;
}
UserCtrl.$inject = ['$log'];
angular.module('app').controller('UserCtrl', UserCtrl);
I hope this is what, is required.
Related
I didn't found some code that can help me among all answers about the subject.
My level in AngularJS is 0 so I don't understand the code too ^^
It's not my code : I have to debug/correct it :
I have a ng-repeat and a button to add a div as many times I want.
The initial div selected by default the first "Act" and the additionnal div has the first choice
<option value="">Select</option> selected and that's what I want.
<div ng-repeat="item in vm.ListActs track by $index">
<fieldset>
<legend>Act {{$index + 1}}<i class="icon-close" ng-click="vm.DeleteAct($index)" ng-hide="$index === 0"></i></legend>
<br />
<div class="field selectField">
<label for="selectgroupAct{{$index}}">
TO <span class="obligatoire">*</span>
</label>
<select id="selectgroupAct{{$index}}"
name="selectgroupAct{{$index}}"
ng-options="act.Code as acte.Code for acte in vm.ListActsTO.Acts"
ng-disabled="vm.ListActsTO.Acts.length === 1"
ng-model="item.Code"
ng-change="vm.ActIndexChange($index, item.Code)"
required >
<option value="">Select</option>
</select>
</div>
</fieldset>
</div>
Do you know why the initial select doesn't want to have the <option value="">Select</option> as the selected option ?
In the js I have this code:
(function () {
'use strict';
angular
.module('SpaApp')
.controller('myController', myController);
myController.$inject = ['firstService', 'secondService', '$localStorage', '$location'];
function myController(firstService, secondService, $localStorage, $location) {
var $ctrl = this;
angular.extend($ctrl, {
...methods declared
});
init();
return $ctrl;
function init() {
angular.extend($ctrl, {
ListActsTO: {},
ListActs : []
});
getListActsTO();
$ctrl.ListActs [0] = {
Code: ""
};
}
...
I tried to add property selected in my option <option value="">Select</option> but it didn't work. I tried with https://docs.angularjs.org/api/ng/directive/select but I'm not good enough and after applying one, the other functionnalities I have didn't work anymore.
Thank you for your help
The ng-model is the key here. It says 'item.Code is the variable being tracked in this form element'.
<select id="selectgroupAct{{$index}}"
...
ng-model="item.Code"
...
required >
That said, in your controller, you can simply initialize this variable to match the value, in this case an empty string.
function myController(firstService, secondService, $localStorage, $location) {
var $ctrl = this;
$ctrl.item = {Code: ""}
.....
(assuming you don't have other empty string values in your vm.ListActsTO.Acts array)
I mixed EJS and AngularJS in a webapp, but now I'm having problems to load a default value for a dropdown (select element).
I use the same HTML file to add and update users.
I have a URL that return all values loaded in the dropdown, accessed in the Angular controller when the page loads.
This is the controller:
angular.module('app').controller('userCtrl', function($scope, $http) {
...
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
});
}
The EJS sends the default value via response (as in this example):
router.get('/user', function(req, res) {
res.render('pages/user', { defatultCity: 10 });
}
The HTML builds the dropdown with this code:
<select id="city" name="city" class="form-control input-sm" required>
<option></option>
<option ng-repeat="x in cities" value="{{x.idCidade}}"> {{ x.Nome }} </option>
</select>
What I have 'unsuccessfully' tried so far (in the HTML):
To validate value from Angular with value from EJS
<option ng-repeat="x in cities" value="{{x.idCity}}" <%if (defaultCity == %> {{x.idCity}} <%) {%> selected <%}%> > {{ x.Nome }} </option>
To insert a hidden input to hold the value in the HTML and inside the controller I added a JQuery
<input type="hidden" id="defaultCity" value"<%=defaultCity%>" />
// In the controller (it return an error - this.each is not a function)
$('city').val($('#defaultCity'))
I know these attempts are ugly, but I could not find a way to make it work yet. I'll be happy if someone knows how to do it.
PS: I would like to avoid passing all the city list of values from NodeJS to use EJS forEach command inside the HTML.
Thank you!
Add this piece of code at the end of your .ejs template
<script type="text/javascript">
angular.module('app')
.value('myCity', <%- JSON.stringify(defaultCity) %>);
</script>
then inject the component in your controller:
app.controller('myCtrl', function ($scope, myCity) {
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
// myCity must be an object - same as vm.cities[0], for example
$scope.defaultCity = myCity;
});
});
and change your HTML file to have the default value
<select ng-model="defaultCity"
ng-options="city as city.name for city in cities track by city.id"
id="city" name="city" class="form-control input-sm" required >
<option></option>
</select>
I am creating a custom filter in angular js this is my html,
<div class="box-body">
<div class="form-group">
<label>Page-Title:</label>
<input type="text" required value="" data-ng-model="title" name="page_title" class="form-control" id="" placeholder="Enter Page Title">
</div>
<div class="form-group">
<label>Page-Alias:</label>
<input type="text" value="#{{ title | replaceSpace}}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
</div>
This is my angular js code
var app = angular.module('CustomAngular', []);
app.controller('CustomCtrl', function ($scope) {
app.filter('replaceSpace', function () {
return function (input) {
return input.replace(/ /g, '-').toLowerCase();
};
});
});
The filter is not working and also I get error in the console.
Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=slugifyFilterProvider%20%3C-%20slugifyFilter
at Error (<anonymous>)
If I use filter: infront of the filter name I donot get any errors in console but it's still not working.
<input type="text" value="#{{ title | filter:replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
You don't put filters inside of a controller, put it after your var app line. It's a separate thing just like controllers / directives / etc.
var app = angular.module('CustomAngular', []);
// Here's where it goes
// Also now any/all controllers can use it!
app.filter('replaceSpace', function () {
return function (input) {
return input.replace(/ /g, '-').toLowerCase();
};
});
app.controller('CustomCtrl', function ($scope) {
});
You should define filter outside of controller and not use filter: as it has different meaning, that's the correct way to use your filter
<input type="text" value="#{{ title | replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
although you should either initialize model by $scope.title = '' or place a check in your filter to run replace only when input is defined, otherwise you will get JS errors
filter: is used to filter the array from model, and when you pass another filter to it it does nothing
I'm trying to show some editable results to the users, so I show them through an input field. This is a basic example of what I'm doing:
<div class="form-group">
<label>First number</label>
<input type="text" ng-model="first" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>Second number</label>
<input type="text" ng-model="second" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>The sum is: {{first + second }}</label>
<input type="text" ng-model="result" ng-required="true" class="form-control">
</div>
In the result's div, I used a label to test if the result is being obtained correctly, and it is. But if I edit the first or second values, the input's result doesn't update.
This is the controller used (yeah, the form is in a modal):
var ModalInstanceCtrl = function ($scope, $modalInstance) {
$scope.result = $scope.first + $scope.second;
$scope.confirm = function () {
$modalInstance.close(result);
};
$scope.cancelNewBet = function () {
$modalInstance.dismiss('cancel');
};
};
I thought the value was supposed to get automatically updated once I define how it is obtained. But clearly it misses something to change the result through script...
Thanks in advance.
What do you want to happen when the user edits the results input? Do you want the data binding to break (I assume not and ignore this possibility)? Do you want one of the inputs to adjust to the proper value?
If you only want to display the output, do this, in your controller:
$scope.result = function() { return $scope.first + $scope.second; }
And in your view:
{{ result() }}
But if you want the user to be able to edit the result and (let's say) have second be assigned (result - first), then you'd want something like this in your view (by the way, note the type="number"):
<input type="number" ng-change="adjustResult()" ng-model="first">
<input type="number" ng-change="adjustResult()" ng-model="second">
<input type="number" ng-change="adjustInput()" ng-model="result">
And in your controller:
$scope.adjustResult = function() {
$scope.result = $scope.first + $scope.second;
};
$scope.adjustResult(); // initialize result
$scope.adjustInput = function() {
$scope.second = $scope.result - $scope.first;
}
I have problem with angular modal value.
I have $rootScope and on button im opening modal which contains , and I can't set default / selected value to that
<form>
<input type="button" class="mobileUpdate" ng-click="openMobileUpdateModal()" />
<script type="text/ng-template" id="mobileModal.html">
<form name="modalForm">
<div class="modal-body">
<p>Country</p>
<select id="countryMobile" ng-model="countryMobile" class="select-styled" name="countryMobile" required>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
</div>
</div>
<div class="modal-footer">
<input type="button" ng-click='confirm()' value="OK"/>
<input type="button" ng-click='cancel()' value="Cancel"/>
</div>
</form>
</script>
</form>
$rootScope.openMobileUpdateModal = function () {
$rootScope.countryMobile = $rootScope.country;
var modalInstance = $modal.open({
templateUrl: 'mobileModal.html',
controller: ModalInstanceCtrl
});
};
var ModalInstanceCtrl = function ($rootScope, $modalInstance) {
$rootScope.confirm = function () {
//do something
$modalInstance.close();
};
$rootScope.cancel = function () {
$modalInstance.dismiss();
};
};
Anyone know how to send value from $rootScope to modal, and set that value as default?
Thanks
First of all there is syntax error you have double quote twise in you select tag code. Update it as below then try. And use $root in your ng-model.
<select id="countryMobile" ng-model="$root.countryMobile" class="select-styled" name="countryMobile" required>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
I'm not sure that I understand your problem correct but try do not use rootScope or modify and avoid rootScope modification.
If you need use some value from rootScope:
extract this value to local scope of particular controller and
after that use it
Use WATCH operator to avoid situations when you
render some value before it initialised.
<option ng-repeat> does not work in angularjs.
you should use
<select id="countryMobile" ng-model="countryMobile" class="select-styled" name="countryMobile" required ng-options="country.id as country.name for country in contries"></select>
http://docs.angularjs.org/api/ng/directive/select