ng-value doesnt submit the right value - angularjs

here's my view
div class="mdl-cell--12-col chat__list" >
<div class="mdl-cell--12-col" ng-repeat="listRoom in itemsList track by $index">
<ul>
Channel name : {{listRoom[0]}}
<li ng-repeat="x in listRoom[1]" >
<p>MESSAGE : {{x.message_text}}
</div>
</li>
</ul>
<form name="haha{{$index}}">
<input type="hidden" type="text" ng-model="item.admin_id" />
<input type="hidden" type="text" ng-value="item.channel_name = listRoom[0]" ng-model="item.channel_name "/>
<textarea ng-keydown="$event.which === 13 && addRoom()" placeholder="Type Your Message Here" ng-model="item.message_text"></textarea>
<button class="send__chat col-lg-2 pull-right" ng-click="addRoom()">Send</button>
{{item | json }}
</form>
</div>
Here's example my controller
$scope.itemsList =[{
"blp-crdtcrd-46": {
"message_text": "hai",
},
"blp-crdtcrd-47": {
"message_text": "halo",
}, "blp-crdtcrd-48": {
"message_text": "what",
},
}];
$scope.item={};
$scope.addRoom = function(){
$scope.item.admin_id = 1;
$scope.item.user_id = 0;
chatService.AddChat($scope.item);
}
My problem is every time i submit the form ,the ng-value of item.channel_name always submit blp-crdtcrd-48 and not dynamic,i have 3 channels in my array , and it always submit blp-crdtcrd-48 .I'm using {{ item | json }} to show the ng-value before submit and it show the corret value , when i'm hit the submit button the value result always blp-crdtcrd-48
help me and i'm appreciate all ur comment and help thank you very much

Related

create objects on form submit in typescript angular 7

I am trying to create 2 separate objects on form submission. Below is my code:
test.html
<form [formGroup]="gamificationForm" (ngSubmit)="onSubmit()">
<div *ngFor="let medal of medalResponse; let iMedal=index" class="row col-lg-12 mtop-custom-10 medal-level-point-config">
<input type="hidden" class="point-text" [(ngModel)]="medal.medalId" formControlName="medalId" />
<div class="col-lg-4 col-6">
{{medal.medalName}}
<input type="hidden" class="point-text" [(ngModel)]="medal.medalName" formControlName="medalName" />
</div>
<div class="col-lg-4 col-6">
<input type="number" class="point-text" [(ngModel)]="medal.points" formControlName="points" />
</div>
</div>
<button class="custom-btn-class" name="submit" type="submit">Save</button>
</form>
Typescript:
gamificationForm = this.fb.group({
medals: this.fb.group({
medalId: [''],
medalName: [''],
points: ['']
})
});
onSubmit() {
console.warn(this.gamificationForm.value);
}
JSON:
It is printing last values from the loop on html page and in json too.
You can convert this JSON value to your required format,
format(value) {
return [
{
Level: [
{
"levelId-0":value.levelId-0,
"level-0":value.level-0,
"points-0":value.points-0
},
....
],
Medal: [
.....
]
}
]
}
Unfortunately I haven't done this via Template-driven Forms, but here my ideas:
You will need to group your fields into the Level and Medal arrays by wrapping your *ngFor into a <ng-container formArrayName="Level"> container and try it.
Each *ngFor should set the position FormArray, but you will need to experiment and see if the formArrayName directive does it for you.
Happy ng-coding!

Binding values from ng-repeat in Angularjs

I'm loading data from a database and save it to an array as follows:
$scope.allGroups = [{id: 1, groupName: group1}, {id: 2, groupName: group2}, ..]
In my view, I'm trying to select multiple group names as follows:
<div
class="drag-container avaliable-groups-connect groups-container schedule-container"
>
<div class="group" ng-repeat="m in allGroups">
<input type="checkbox" ng-model="m.selected" />
<span>{{ m.groupName }}</span>
</div>
</div>
I want to save selected items (m.selected) to an array one-by-one and bind that array to ng-model="schedule.selectedGroups"
How can I perform that? Thank you..
<div class="group" ng-repeat="m in allGroups" ng-init="m.selected = false">
<input type="checkbox" ng-model="m.selected" />
<span>{{ m.groupName }}</span>
</div>
Now your checkbox ng-model with modify the variable to true or false and in your js code
you can do like below.
$scope.schedule.selectedGroups = $scope.allGroups.filter(function (data) {
return data.selected === true;
});

how to select one primary contact on listing of contacts in ng-repeat by radio button

I have list of contacts and repeating with ng-repeat how to make one primary contact by selecting radio button .
<div class="col-sm-12" ng-repeat='contact in acc.contacts'>
<div class="col-xs-2" ng-class="{'error':(sub && !contact.isPrimary)}">
<input type="radio" name='isPrimary' ng-model='contact.isPrimary' ng-value="true">
</div>
<div class="col-xs-2" ng-class="{'error':(sub && !contact.name)}">
<input type="text" ng-model='contact.name'>
</div>
</div>
</div>
my json is look like
{
"contacts": [
{
"isPrimary": false,
"name": null,
},
{
"isPrimary": false,
"name": null
},
{
"isPrimary": false,
"name": null
]
}
i want isPrimary should be true for one , but it does not set false when radio button got deselected
Because you use the radio button in an ng-repeat and the ng-model is a property of the repeated item, you can do it like this:
<div class="col-xs-2" ng-class="{'error':(sub && !contact.isPrimary)}">
<input type="radio" name='isPrimary'
ng-value="true"
ng-change="primaryClicked(contact)">
</div>
And in your controller:
$scope.primaryClicked = function(contact) {
// Set all others on false
for (var i = 0; i < $scope.acc.contacts.length; i++) {
$scope.acc.contacts[i].isPrimary = false;
}
// Set current on true
contact.isPrimary = true;
}
The correct approach is to use ng-value.
Modify your code:
<label data-ng-repeat="contact in acc.contacts">
<input type="radio" data-ng-model="contact.isPrimary" data-ng-value="true" />
{{contact.name}}
</label>
Hope this is helps you

How to get dynamic ng-model from ng-repeat in javascript?

I'm developoing a web app and stuck here:
Part of the HTML:
<div class="input-group">
<select name="select" class="form-control input-group-select" ng-options="key as key for (key , value) in pos" ng-model="word.pos" ng-change="addPos()">
<option value="">Choose a POS</option>
</select>
<span class="sort"><i class="fa fa-sort"></i></span>
</div>
<ul class="listGroup" ng-show="_pos.length > 0">
<li class="list" ng-repeat="item in _pos track by $index">
<span>
{{item.pos}}
<span class="btn btn-danger btn-xs" ng-click="delPos($index)">
<span class="fa fa-close"></span>
</span>
</span>
<!-- I wanna add the input which can add more list item to the item.pos-->
<div class="input-group">
<a class="input-group-addon add" ng-class=" word.newWordExp ? 'active' : ''" ng-click="addItemOne()"><span class="fa fa-plus"></span></a>
<input type="text" class="form-control exp" autocomplete="off" placeholder="Add explanation" ng-model="word.newWordExp" ng-enter="addExpToPos()">
{{word.newWordExp}}
</div>
</li>
</ul>
Part of the js:
$scope._pos = [];
$scope.addPos = function () {
console.log("You selected something!");
if ($scope.word.pos) {
$scope._pos.push({
pos : $scope.word.pos
});
}
console.dir($scope._pos);
//console.dir($scope.word.newWordExp[posItem]);
};
$scope.delPos = function ($index) {
console.log("You deleted a POS");
$scope._pos.splice($index, 1);
console.dir($scope._pos);
};
$scope.addItemOne = function (index) {
//$scope.itemOne = $scope.newWordExp;
if ($scope.word.newWordExp) {
console.log("TRUE");
$scope._newWordExp.push({
content: $scope.word.newWordExp
});
console.dir($scope._newWordExp);
$scope.word.newWordExp = '';
} else {
console.log("FALSE");
}
};
$scope.deleteItemOne = function ($index) {
$scope._newWordExp.splice($index, 1);
};
So, what am I wannt to do is select one option and append the value to $scope._pos, then display as a list with all of my selection.
And in every list item, add an input filed and add sub list to the $scope._pos value.
n.
explanation 1
explanation 2
explanation 3
adv.
explanation 1
explanation 2
So I don't know how to generate dynamic ng-model and use the value in javascript.
Normaly should like ng-model="word.newExplanation[item]" in HTML, but in javascript, $scope.word.newExplanation[item] said "item is not defined".
can any one help?
If I've understood it correclty you could do it like this:
Store your lists in an array of object this.lists.
The first object in the explanation array is initialized with empty strings so ng-repeat will render the first explanation form.
Then loop over it with ng-repeat. There you can also add dynamically the adding form for your explanation items.
You can also create append/delete/edit buttons inside the nested ng-repeat of your explanation array. Append & delete is already added in the demo.
Please find the demo below or in this jsfiddle.
angular.module('demoApp', [])
.controller('appController', AppController);
function AppController($filter) {
var vm = this,
explainTmpl = {
name: '',
text: ''
},
findInList = function (explain) {
return $filter('filter')(vm.lists, {
explanations: explain
})[0];
};
this.options = [{
name: 'option1',
value: 0
}, {
name: 'option2',
value: 1
}, {
name: 'option3',
value: 2
}];
this.lists = [];
this.selectedOption = this.options[0];
this.addList = function (name, option) {
var list = $filter('filter')(vm.lists, {
name: name
}); // is it in list?
console.log(name, option, list, list.length == 0);
//vm.lists
if (!list.length) {
vm.lists.push({
name: name,
option: option,
explanations: [angular.copy(explainTmpl)]
});
}
};
this.append = function (explain) {
console.log(explain, $filter('filter')(vm.lists, {
explanations: explain
}));
var currentList = findInList(explain);
currentList.explanations.push(angular.copy(explainTmpl));
}
this.delete = function (explain) {
console.log(explain);
var currentList = findInList(explain),
index = currentList.explanations.indexOf(explain);
if (index == 0 && currentList.explanations.length == 1) {
// show alert later, can't delete first element if size == 1
return;
}
currentList.explanations.splice(index, 1);
};
}
AppController.$inject = ['$filter'];
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="appController as ctrl">
<select ng-model="ctrl.selectedOption" ng-options="option.name for option in ctrl.options"></select>
<input ng-model="ctrl.listName" placeholder="add list name" />
<button class="btn btn-default" title="add list" ng-click="ctrl.addList(ctrl.listName, ctrl.selectedOption)"><i class="fa fa-plus"></i>
</button>
<div class="list-group">Debug output - current lists:<pre>{{ctrl.lists|json:2}}</pre>
<div class="list-group-item" ng-repeat="list in ctrl.lists">
<h2>Explanations of list - {{list.name}}</h2>
<h3>Selected option is: {{ctrl.selectedOption}}</h3>
<div class="list-group" ng-repeat="explain in list.explanations">
<div class="list-group-item">
<p class="alert" ng-if="!explain.title">No explanation here yet.</p>
<div class="well" ng-if="explain.title || explain.text">
<h4>
{{explain.title}}
</h4>
<p>{{explain.text}}</p>
</div>Title:
<input ng-model="explain.title" placeholder="add title" />Text:
<input ng-model="explain.text" placeholder="enter text" />
<button class="btn btn-primary" ng-click="ctrl.append(explain)">Append</button>
<button class="btn btn-primary" ng-click="ctrl.delete(explain)">Delete</button>
</div>
</div>
</div>
</div>
</div>

Get data, change one single element and return to api

I get Data from an api and easily list them, now i want to change one element of those, to "default". I dont know how to control that,
Here is the js.
$scope.updateDefault = function() {
if (AuthService.isAuth()) {
Account.one().get().then(
function(account) {
**account.data.defaultMsisdn= $scope.element.isSelected;
$log.d("account: ", account.data);
account.data.put();**
}
);
}
};
here is the HTML:
<div id="container" style="width:650px">
<ol ng-repeat="element in accountmsisdn">
**<li style=" text-align:left; float:left">
<input type="radio" ng-model="element.isSelected" ng-click="updateDefault()">
<span>{{element.msisdn}} </span>
</li>**
<li style="text-align:center;float: inside" ng-switch="element.active">
<span ng-switch-when=true>
{{'view.settings.sender.active'| translate}}</span>
<span ng-switch-when=false>
{{'view.settings.sender.notactive'| translate}}</span>
<span ng-switch-default>
<strong> - </strong> </span>
</li>
You need to pass the current element as an argument to updateDefault(), so it knows what element to update:
<input type="radio" ng-model="element.isSelected" ng-click="updateDefault(element)" />
$scope.updateDefault = function (element) {
...
account.data.defaultMsisdn = element.isSelected;
..
};

Resources