I have a select option where I get a list of titles i.e. Mr, Mrs, Dr etc. from an API, the code looks like this in the front end:
<select class="form-control" name="titleSelect" id="titleSelect" ng-options="option.value for option in titleData.availableOptions track by option.key" ng-model="adult[$index].selectedTitle" ng-init="adult[$index].selectedTitle = titleData.availableOptions[0]"></select>
And this in the controller:
var getPassengerTitle = PassengerDetailsAndCardDetailsService.getPassengerTitle();
PassengerDetailsAndCardDetailsService is service, where I get the API data i.e. the title data. Furthermore this service returns a promise.
This is where I set the title Data:
getPassengerTitle.then(function(result){
$scope.availableTitles = angular.fromJson(result.titleList);
$scope.tempListOfTitles = [];
for(var key in $scope.availableTitles){
$scope.tempListOfTitles.push({key : key, value : $scope.availableTitles[key]});
};
$scope.titleData = {
availableOptions: $scope.tempListOfTitles,
};
});
When I try to ng-init to the first option (that is Mr.) it does not work as in a blank option is shown. However when I tried statically defining the titleData in an object it works, could you please help me?
UPDATE:
I failed to mention that the title data is inside an ng-repeat to support input for multiple people/passengers in this case. Therefore I'm using adult[$index] where it creates an ng-model for each person/passenger.
I am not sure if this is the required behavior you want, but if you want to initialise the title on selecting an option you can either use the value from ng-model or use the event handler ng-change. Here is an example jsbin which handles the change and assigns the new value to ng-model. Let me know if this is what you were looking for
try like this.
var myapp = angular.module('app', []);
myapp.controller('Main', function ($scope) {
var vm = this;
vm.adult = {
'selectedTitle':'1'
};
vm.titleData = [
{'key':'0','value':'Mr'},
{'key':'1','value':'Ms'},
{'key':'2','value':'Dr'}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app">
<div ng-controller="Main as ctrl">
<div class="select-style">
<select ng-options="option.key as option.value for option in ctrl.titleData" ng-model="ctrl.adult.selectedTitle"></select>
</div>
</div>
</div>
Related
Console screenshot I'm having a problem with my code; I'm getting values upon clicking the button, and the same values are also showing in the console. However, I can't see the same values in the input field. Can anyone help with this?
$scope.getFees = function (id) {
getClients.getFeesPoints(id).then(function(response) {
$scope.fees = response.data.fees;
console.log($scope.fees);
});
};
<input type="text" ng-model="fees" class="mdltb-inp fee-inp"
name="fees" placeholder="35$" >
Check link of image 30 is the value of response data
Remove value="{{User}}" from the code and verify $scope.fees = response.data; binds a text value and not an object.
In case if the response.data is an object, that won't bind to an input text field. Find out the appropriate key from response.data object and bind input with that key. Also if the value is not binded still try to call $scope.$apply() after assigning the value
I this you should try this way
var app = angular.module("myapp", []);
app.controller("myCtrl", ['$scope', function($scope) {
$scope.fees="new";
$scope.getFees = function (id) {
//getClients.getFeesPoints(id).then(function(response)
//{
$scope.fees = 50;
console.log($scope.fees);
//});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="myCtrl">
<input type="text" class="form-control" id="inputValue" name="uservalue" ng-model="fees" ng-required="true" autofocus="true" ng-blur="checkIfValid()"/>
<button ng-click="getFees(true)">Demo</button>
<h1>{{fees}}</h1>
</div>
</div>
I have Solved this by using $rootScope i.e. "$rootScope” is a parent object of all “$scope” angular objects created in a web page.
let me explain my scenario. I am having the dropdownlist in my master page. if changed dropdownlist the data are changed depend upon the dropdownlist value.
If i refreshed my page or moved to another page the dropdownlist will clear automatically.
I want to retain the dropdownlist value after refresh the page or moved to another page.
I tried like this but this is not help ful.
HTML
<select id="Facility_ID" required typeof="text" name="Facility Name" ng-options="Role.FacilityName for Role in Roles"
form="DistanceMatrixFormId" class="form-control" ng-model="Role._id" ng-selected="getFacilityID(Role._id.FacilityName)">
</select>
Controller.js
$scope.getFacilityID = function (data) {
localStorage.setItem("FacilityName", data);
var getfacility = localStorage.getItem("FacilityName");
}
i refered this link but it is not help ful
I don't know how to retain the value. can any one fixed me.
You cannot put an object into the local storage, you must store strings inside local storage.
If you want, you can have an implementation I did here : How to add local storage in angular?
For your current code, you don't need to use ng-selected. ng-model is enough.
<select id="Facility_ID" required typeof="text"
name="Facility Name"
ng-options="Role.FacilityName for Role in Roles"
form="DistanceMatrixFormId"
class="form-control"
ng-model="Role._id"
ng-change="updateLocalStorage()">
</select>
And inside your angular controller, what you can do is the following :
myApp.controller('controllerName', ['$scope', 'LocalStorageService',
function($scope, LocalStorageService){
// After initialization of your "Role" object
$scope.Role._id = LocalStorageService.retrieve('mySelectValue');
$scope.updateLocalStorage = function(){
LocalStorageService.store('mySelectValue', $scope.Role._id);
}
}])
Here is an example that uses a service to store the selected value. Unfortunately the embedded demo does not work because of the sandboxing, but works when served as an application.
angular.module(
"App", []
).factory("MyStorage", function() {
const key = "selected";
return {
getValue: function() {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : null;
},
setValue: function(value) {
localStorage.setItem(key, JSON.stringify(value));
}
};
}).controller("MyCtrl", function($scope, MyStorage) {
$scope.options = ["A", "B", "C"];
$scope.selected = MyStorage.getValue();
$scope.$watch("selected", newValue => {
MyStorage.setValue(newValue);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="App" ng-controller="MyCtrl">
<select ng-model="selected" ng-options="x for x in options">
</select>
</div>
My angular experience is basically about 3 days part time, so there's probably something simple I'm missing here.
I'm trying to create a dynamic list of multiple inputs based on an array, which I then want to reference from elsewhere in the app. What I've tried is loading a template from a custom directive, then $compile-ing it.
<input data-ng-repeat="term in query" data-ng-model="term">
My controller contains $scope.query = [""] which successfully creates the first empty input box. But the input box doesn't seem to update $scope.query[0] when I modify it. This means that when I try to create another empty input box with $scope.query.push(""); (from a keypress listener looking for the "/" key) I get a "duplicates not allowed" error.
I've tried manually listening to the inputs and updating scope.$query based on their value, but that doesn't feel very "angular", and results in weird behaviour.
What do I need to do to link these values. Am I along the right lines or way off?
I made a simple jsfiddle showing how to use an angular model (service) to store the data. Modifying the text inputs will also modify the model. In order to reference them somewhere else in your app, you can include TestModel in your other controllers.
http://jsfiddle.net/o63ubdnL/
html:
<body ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="item in queries track by $index">
<input type="text" ng-model="queries[$index]" />
</div>
<br/><br/>
<button ng-click="getVal()">Get Values</button>
</div>
</body>
javascript:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope, TestModel)
{
$scope.queries = TestModel.get();
$scope.getVal = function()
{
console.log(TestModel.get());
alert(TestModel.get());
}
});
app.service('TestModel', function()
{
var queries = ['box1','box2','box3'];
return {
get: function()
{
return queries;
}
}
});
I tried to get the HTML page value to angularJS function , The below steps are which i tried.
HTML page :
<label class="item-input item-stacked-label">
<span class="input-label cont_det_label">First Name</span>
<p class="contact_display" id="txtFirstName" ng-model="testName">Satya</p>
</label>
angularJS Page :
.controller('SocialNetworkCtrl', ['$scope','$http','$state','ContactsService','$ionicNavBarDelegate','$ionicLoading','$ionicPopup',function($scope, $http, $state, ContactsService, $ionicNavBarDelegate, $ionicLoading,$ionicPopup) {
$scope.showUserProfile = function() {
$state.go("linkedin");
var firstname = (document.getElementById("txtFirstName").value);
}
}])
So I need var firstname = Satya ?? Is it correct way please guide me to access this value .
var firstName = $scope.testName
<input ng-model="testName" />
testName is the ng-model name that you have give. It will be automatically binded to your controller. No need the get the value using document.getElementById
Wrong usage , why ng-model in <p> tag??
Update
Change your fiddle with the following code, it will work. Also make sure framework is selected properly (as in the image)
<div ng-app ng-controller="testController">
<input ng-model="testDataName" ng-change="check()" /> {{testDataName}}
After ng-change : {{checkName}}
</div>
function testController($scope) {
$scope.testDataName="Dummy Name";
$scope.check = function () {
$scope.checkName=$scope.testDataName;
console.log($scope.checkName);
};
}
its a text node, you will require .innerHTML or '.innerText', .value is for form inputs
var firstname = (document.getElementById("txtFirstName").innerHTML);
and don't use ng-model on a p element, change it to like this
<p class="contact_display" id="txtFirstName">{{testName}}</p>
just use $scope.testName to get the value, no need for firstname = (document.getElementById("txtFirstName").innerHTML); querying DOM for value is jQuery style, use angular the $scope for 2 way bindings
Read more at official doc
Update here is updated function on loginCtrl
.controller('loginCtrl', ['$scope', function ($scope) {
$scope.testNameData = 'Satya';
$scope.doLogin = function() {
alert($scope.testNameData);
};
}])
If you really want to go jQuery way here is what you can do, its not recommended, you should use angular directive to do DOM manipulation
$scope.showUserPro = function() {
$ionicLoading.show();
// Here i need the value of <p tag>
var name = document.getElementById("txtFirstName"),
firstNameFromHtmlPtag = name.innerText;
console.log(firstNameFromHtmlPtag, 'Doing API Call 1');
}
The problem is that SecondName attribute is not updating when I input text in the field.
please look at this code at jsfiddle: http://jsfiddle.net/HEdJF/253/
HTML:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<div>
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>FirstName is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl as Second">
SecondName: {{Second.Data.SecondName}}<!-- How do I automatically updated it here? -->
</div>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.service('Data', function(){
var obj;
return obj = { FirstName: '54',
SecondName: '22',
f: function(){
obj.FirstName = '1';
obj.SecondName = obj.FirstName;
}
};
});
myApp.controller('FirstCtrl', function( $scope, Data ){
Data.f();
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( Data ){
Second = this;
Second.Data = Data;
});
It's not going to work like you think it should. This line:
obj.SecondName = obj.FirstName;
creates a new property SecondName equal by value to the FirstName. However since both properties are primitive types (String) there is no connection between them. In other words obj.SecondName does not reference obj.FirstName.
You have two options.
Option 1. (bad) Set up additional watcher on FirstName change, and once that happens update SecondName respectively
$scope.$watch('Data.FirstName', function() { Data.SecondName = Data.FirstName; });
http://jsfiddle.net/HEdJF/254/
Option 2. Don't introduce additional watchers and change your architecture. For example, use FirstName in the second controller too, since they are supposed to be equal.
http://jsfiddle.net/HEdJF/255/
This is a scoping issue because of your nested scopes. Take a look at this website for a clear explanation: http://toddmotto.com/digging-into-angulars-controller-as-syntax/. There's a few different solutions to solve your problem under the Nested Scopes section.
The problem with your code is that the First Controller is just changing the value of Data.FirstName object, hence the changes are not reflecting on your second controller because the value of SecondName does not change after it is initialized in the first controller. So you have to set your Data.SecondName
in your data as well.
Alternatively, you can do this.
<div>
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>FirstName is : <strong>{{Data.SecondName=Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
You can also use directives to achieve this functionality, but I guess you are just looking for the above solution.
Cheers!