I would like to store the value of a selection from a dropdown in AngularJS.
I am able to replicate the new selection on UI but not in console.
<div ng-controller="MyCtrl">
<div>
Fruit List:
<select id="fruitsList"
ng-model="cart"
ng-change="getSelectedLocation()"
ng-options="state for state in shelf"></select>
<br/>
<tt>Fruit selected: {{cart}}</tt>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.cart = "";
$scope.shelf = ['Banana', 'Apple', 'Pineapple', 'Blueberry'];
$scope.getSelectedLocation = function() {
console.log($scope.cart);
}
$scope.printSelectedValue = function() {
if ($scope.cart == 'Banana') {
console.log("Its a banana")
} else if ($scope.cart == "Apple") {
console.log("Its an apple")
} else {
console.log("Its neither a banana nor an apple")
}
}
});
Any idea on how to achieve that?
jsfiddle link
You're printing the cart once, when the controller is instanciated. At that time, the user hasn't had the chance to select anything yet.
If you want to print the selection every time it changes, use ng-change (you're already using it, BTW):
ng-change="printSelection()"
and in the controller:
$scope.printSelection = function() {
console.log($scope.cart);
};
Related
I am working on a project which is having a web form using html and angularjs
the backend using java/spring and db oracle.
My form contains few lists say list1,list2...
list1 get its items from db. As soon as user selects the item in list1 ng-change gets trigger and data for list2 geenrates.That means list2 values depends on list1 ng-change directive.After filling all required fields I am saving the form in db.
Now I am giving user a provison that they can see there filled details . So once they click on "edit" they can see all their details. I am using ng-model to bind the data .All fields are working and binding values form db to the html webform except for list2. Can anyone show how can we achieve this.
I am having some issues with hide/show functionality when user wants to see his request in editable mode. Please suggest some workaround.
<div ng-app="myApp" ng-controller="myCtrl">
<label>List1:</label>
<select ng-model="selectedName" ng-change="getList()" ng-options="item for item in names">
</select>
<br>
<label>List2:</label>
<select ng-model="selectedNcomany" ng-options="item for item in comany">
</select>
<button ng-click="editText()">
Edit
</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
var db = {};
$scope.getList = function(){
if($scope.selectedName == "Linus"){
$scope.comany = ["!","2"];
}
else{
$scope.comany =["0"]
}
}
$scope.editText = function(){
$scope.selectedName = "Linus";
$scope.selectedNcomany = "1";
}
});
</script>
https://jsfiddle.net/31d8cv92/12/
I work in the similar environment we created a service show field which looks like this
angular.module('test').service('showField',showField);
function showField(){
this.showfield = function(fieldData,pagemode){
if(angular.isDefined(fieldData) && fieldData.hasOwnProperty('hide')){
if (fieldData.hide) {
if (fieldData.npi) {
if (pagemode == 'view') {
return false;
}else {
return true;
}
} else {
return false;
}
} else {
return true;
}
}
}
}
We invoke this in our required controllers for view mode and update mode.
**(New to AngularJS)
I'm retrieving a list of objects (item) from a Django API.
my_app.factory('list_of_items', function($resource) {
return $resource(
'/api/petdata/') });
Then I display everything in a html page within a ng-repeat:
<div ng-controller="ModalDemoCtrl">
<div ng-repeat="item in items | filter:{display:'1'} | orderBy: 'item_name'">
<div class="box box-widget widget-user">
{{ item.pet_name }}{% endverbatim %}
<button type="button" class="btn btn-box-tool" ng-click="askDelete(item)" href="#"><i class="fa fa-times"></i></button>
</div>
<div>
Everything's fine so far.
Then I want the user to be able to delete one of the item by clicking on the button from the html page.
What means deleting here :
1. Update the API database by changing the property "display:1" to "display:0".
2. Remove the item from the ng-repeat.
I want to make a "Are you sure" modal to confirm the delete process.
This is the askDelete function.
angular.module('djangular-demo').controller('Ctrl_List_Of_Pets', function($scope, $http, $window,$filter,list_of_pets,pet_by_id,$uibModal) {
$scope.items = list_of_items.query()
$scope.askDelete = function (idx,item,size,parentSelector) {
// console.log("PET",$scope.pet_to_be_undisplayed);
var parentElem = parentSelector ?
angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'LOL',
ariaDescribedBy: 'modal-body',
templateUrl: "myModalContent.html",
controller: function($scope) {
$scope.ok = function() {
modalInstance.close();
};
$scope.cancel = function() {
modalInstance.dismiss('cancel');
};
},
size: size,
appendTo: parentElem,
resolve: {
}
});
modalInstance.result.then(function() {
reallyDelete(item);
});
};
var reallyDelete = function(item) {
$scope.entry = items_by_id.get({ id: item.id }, function() {
// $scope.entry is fetched from server and is an instance of Entry
$scope.entry.display = 0;
$scope.entry.$update({id: $scope.entry.id},function() {
//updated in the backend
});
});
$scope.items = window._.remove($scope.items, function(elem) {
return elem != item;
});
};
});
What works :
Updating the DB works with a PUT request (code hasn't been provided).
What doesn't work :
Removing the item from the ng-repeat never works. Or it throws me an error like here because it doesn't know window._.remove or it doesn't know $scope.items. It depends from what I try. Or the modal close and there is no update of the ng-repeat list, no refresh and every items remain whereas the PUT request to update worked.
I read every article on scope inheritance and I think I didn't make any mistake here but I'm might be wrong. I've been struggling for too long so I post here !
Would you suggest anything to make it work ?
Thank you for your rime.
First:
$scope.askDelete = function (idx,item,size,parentSelector) receives the item index, the item, size, and parent selector... and you are calling ng-click="askDelete(item)"
I assume you are attempting to pass the item, but in askDelete you are receiving as first parameter the index (maybe you should do ng-click="askDelete($index)"?)
Second:
In reallyDelete why are you removing the items array like this:
$scope.items = window._.remove($scope.items, function(elem) {
return elem != item;
});
?
IMHO, it would be a much cleaner code if we just do:
$scope.items.splice(idx, 1) //<- idx would be the idx of the entry in the items
You may want to take a look at Splice
I'm trying to dynamically add a textbox to an Angular form. I'm using ng-repeat and I can add the text box easily by just pushing, an empty string to the array. It will add another textbox, the problem is that ng-model is not syncing the data, and when text is added it remains an empty string.
The text boxes that get created from the initial array sync just fine, it's just the newly added text boxes that are not working.
I've been looking around and one suggestion I saw was to always use a "." when using ng-model, but that didn't work for me.
<div ng-repeat="text in image.text track by $index">
<md-input-container class="md-block" novalidate>
<label>Text {{$index + 1}}:</label>
<textarea md-maxlength="2500" md-midlength="1" required md-no-asterisk name="text"
placeholder="{{text}}"
ng-model="text"></textarea>
</md-input-container>
</div>
Controller:
(function () {
'use strict';
angular
.module('app.article')
.controller('ArticleEditController', ArticleEditController);
ArticleEditController.$inject= ['articleEditDataService', '$routeParams', '$log'];
function ArticleEditController(articleEditDataService, $routeParams, $log) {
var vm = this;
var site = $routeParams.site;
var articleName = $routeParams.article;
var articleRevision_id = $routeParams.revision_id;
vm.data = {};
vm.addNewText = addNewText;
vm.removeText = removeText;
vm.saveArticle = saveArticle;
vm.numMessage = 1;
activate();
function activate(){
getArticle();
}
function getArticle(){
var data = articleEditDataService.getArticle(site, articleName, articleRevision_id);
data.then(function successResponse(res) {
vm.data = res.results.data;
}, function errorResponse (res) {
console.log(res);
});
}
function saveArticle(){
var article = articleEditDataService.postArticle(vm.data, site, articleName, articleRevision_id);
console.log(vm.data);
article
.then(updateArticleSuccess)
.catch(updateArticleError);
}
function updateArticleSuccess(message){
$log.info(message);
}
function updateArticleError(errorMessage){
$log.error(errorMessage);
}
function addNewText (index, key) {
vm.data.content.image_sets[key].text.push("");
}
function removeText (index, key) {
if(vm.data.content.image_sets[key].text.length > 1){
vm.data.content.image_sets[key].text.pop();
}
}
};
})();
initialize the model variable within your controller as an empty object.
then within your text input your ng-model="model[$index]".
I have a following controller
app.controller('MainController', function($scope, $interval,$mdToast, $document, $mdDialog,$timeout,$mdDialog) {
var stops=[
{
stopName:"testinput1",
noOfStudents:2
},
{
stopName:"testinput2",
noOfStudents:2
},
{
stopName:"testinput3",
noOfStudents:4
}
];
$scope.list=stops;
$scope.addStop=function(name,noOfstudent){
stops.push({
stopName:name,
noODstudent:noOfstudent
})
$scope.list=stops;
}
});
in my view I have following code,
<md-list id="stopList">
<md-list-item class="md-3-line" ng-repeat="item in list" style="background:rgb(233, 233, 233);margin:10px;padding-left: 10px;position: relative;min-height: 60px;">
<div class="md-list-item-text">
<h3>{{item.stopName}}</h3>
<h4>{{item.noOfStudents}}</h4>
</div>
<div ng-show="deleteIcon" ng-click="showConfirm($event);" class='delete_icon'></div>
</md-list-item>
</md-list>
The issue I am facing is when I add a stop, the ng-repeat list does not get updated. I want the view to be updated as I add a stop. I am taking the user input from angular material dialog.
Data will be updated automatically in view after you update it in controller. What problem (may be ) you are facing is typo in addStop function.
You have used two dots when updating list. >> $scope..list=stops;
You don't need to push to stop
Just direct push to $scope.list
When stop assigned in the list it'll assign reference if one is updated another will also
$scope.list=stops;
Like this
$scope.list.push({
stopName: name,
noODstudent: noOfstudent
})
Here is a plnkr:
http://plnkr.co/edit/HlzxQ9sqbMbxDiraT22z?p=preview
Seems to be working for me
var name = 'l'
var noOfStudents = 5
$scope.addStop=function(){
stops.push({
stopName:name,
noOfStudents:noOfStudents
})
$scope.list=stops;
}
i have used static data but there should not be any problem
Try this
$scope.addStop = function (name, noOfstudent) {
stops.push({
stopName: name,
noODstudent: noOfstudent
});
$timeout(function () {
$scope.list = [];
$scope.list = stops;
}, 0);
};
there are buttons in detail.html file:
<div ng-controller="test.views.detail">
<div data-ng-repeat="item in details" scroll>
<button ng-click="showDetails(item)">The details</button>
in detail.js file
angular.module('test')
.controller('test.views.detail', function($scope) {
$scope.detailsClicked = false;
$scope.showDetails = function(item){
$scope.detailsClicked = true;
}....
in formDetail.html code:
<div ng-controller="test.views.detail">
{{detailsClicked}}
<div ng-if="detailsClicked">...
Initially it shows false for detailsClicked, when I click on button it goes to showDetails function but value of $scope.detailsClicked never get updated! It is straight forward not sure why it doesn't work:(
This is because you're using the same controller at two places and expecting the scope object to be the same which it is not. Everytime you call ng-controller in your markup a new scope object will be created. If you want them to be based off the same data then use a service.
Here is an example
app.controller('test.views.detail', function($scope, detailsClicked) {
$scope.detailsClicked = detailsClicked;
$scope.showDetails = function(item){
$scope.detailsClicked.isClicked = true;
}
});
Create a factory/service which will retain the data, make sure the data is a
app.factory('detailsClicked', function(){
var data = {
isClicked: false
}
return data;
});