I am newbie with angularjs
I want get data with $resource whitch repeat on html
but there is the error show
"Expected ngRepeat in form of 'item in collection' but got 'user'"
code
<dd ng-repeat= user in User.users>
<input type="radio" value= "{{user.user.userId}}" />
{{user.user.userUsername}}
</dd>
$scope.User= {'user': userService.query()};
please help
return data
User: {
user:
[ {
userId: 1
userName: User1
userUsername: user1
userPassword: 123456
userSex: male
userBirthday: 1999-01-01
userStatus: 1
roleId: 1
roleModel: { }
} ,
{
userId: 2
userName: User2
userUsername: user2
userPassword: 123456
userSex: female
userBirthday: 1888-01-01
userStatus: 1
roleId: 1
roleModel: { }
} ]
}
Try as below:
<div ng-repeat="user in User.user">
<input type="radio" value= "{{user.userId}}" />
{{user.userUsername}}
</div>
Try this
if your userService.query() return collection of objects.
<dd ng-repeat= "user in User.users">
<input type="radio" value= "{{user.userId}}" />
{{user.userUsername}}
</dd>
$scope.User= {'user': userService.query()};
Related
When I check Apple it's all check Pineapple. When I unchecked Pineapple it's also unchecked Apple.
both Tag id different. How can I check only one Apple instead of Pineapple?
var demo = new Vue({
el: '#demo',
data: {
checkedNames: []
},
computed: {
computedNames() {
let names = this.checkedNames;
return names.toString();
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<input type="checkbox" id="50" value="50" v-model="checkedNames">
<label for="Apple">Apple</label>
<input type="checkbox" id="51" value="51" v-model="checkedNames">
<label for="Banana">Banana</label>
<input type="checkbox" id="52" value="50" v-model="checkedNames">
<label for="Pineapple">Pineapple</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
<span>Computed names (reversed order): {{ computedNames }}</span>
</div>
Vue is data-driven. Since both your Apple and Pineapple checkboxes have the same value, Vue considers them to be the same.
It sounds like you want to use separate objects entirely so try this
var demo = new Vue({
el: '#demo',
data: () => ({
options: [{
id: 50,
label: "Apple",
price: 50
}, {
id: 51,
label: "Banana",
price: 51
}, {
id: 52,
label: "Pineapple",
price: 50
}],
selections: []
}),
computed: {
computedNames: ({ selections }) =>
selections.map(({ label }) => label).join(", ")
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<template v-for="fruit in options">
<input
:key="fruit.id"
type="checkbox"
:value="fruit"
v-model="selections"
:id="`fruit_${fruit.id}`"
>
<label :for="`fruit_${fruit.id}`">{{ fruit.label }}</label>
</template>
<br>
<span>Computed names: {{ computedNames }}</span>
<pre>Selections: {{ selections }}</pre>
</div>
var inputs={
'firstname': '',
'lastName':'',
'account':{
'role':'',
'status':''
}
}
This is my model array. I want to display it dynamically in Webpage and by modifying the json array the changes should affect the form too.
Here is the image
UPD:
for your situation, you can use ng-switch to generate elements according to conditions.
Notice(already included in the code snippet):
ng-repeat will generate it's own scope, so your model won't update unless you bind it with the original scope. ref here.
OLD ANSWER:
use ng-model to implement two-way-databinding.
refer the code snippet below:
angular.module("app", []).controller("myCtrl", function($scope) {
$scope.inputs = {
'firstname': 'test first name',
'lastName': 'test last name',
'account': {
'role': 'test role',
'status': 'test status'
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<!-- First Name: <input type="text" ng-model="inputs.firstname"><br>
Last Name: <input type="text" ng-model="inputs.lastName"><br> Account Role: <input type="text" ng-model="inputs.account.role"><br>
Account Status: <input type="text" ng-model="inputs.account.status"><br> -->
<div ng-repeat="(key1, value) in inputs" ng-switch="key1">
<div ng-switch-when="account">
<div ng-repeat="(key2, value2) in value">
{{key1 | uppercase}} => {{ key2 | uppercase}}
<input type="text" ng-model="inputs[key1][key2]">
</div>
</div>
<div ng-switch-default>
{{key1 | uppercase}}
<input type="text" ng-model="inputs[key1]">
</div>
</div>
{{inputs}}
</div>
/My html should look like this/
<head>
<script data-require="angular.js#1.4.1" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<script type="text/ng-template" id="tree-structure">
<label>{{dt}}</label><input type="text" name="" value="{{dt.label}}">
<ul class="childElement">
<li ng-repeat="dt in dt.nodes" ng-include="'tree-structure'">
</li>
</ul>
</script>
<ul class="parentList">
<li ng-repeat="(key, value) in inputs" >
<div ng-repeat="(key1, value1) in value">
<label>{{key1}}</label>
<input type="text" name="" value="{{value1}}">
<!-- <div ng-repeat="(key2, value2) in value1">
<label>{{key2}}</label><input type="text" name="" value="{{value2}}">
</div> -->
</div>
<div ></div>
</li>
</div>
</ul>
</body>
</html>
Some observations :
Your JSON should be formatted properly with type of the field.
If you want to access the object properties as a form fields then it should be structured in a good way so that we can dynamically add the type of the field as well.
[{
name: 'firstName',
type: 'text'
}, {
name: 'lastname',
type: 'text'
}, {
account: [{
name: 'role',
type: 'text'
}, {
name: 'status',
type: 'text'
}]
}]
As your JSON have nested objects. So, first iterate it recursively and create one dimensional array then create the fields using 1D array.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
var inputs = [{
name: 'firstName',
type: 'text'
}, {
name: 'lastname',
type: 'text'
}, {
account: [{
name: 'role',
type: 'text'
}, {
name: 'status',
type: 'text'
}]
}];
$scope.fields = [];
function structuredObj(obj) {
for (var i in obj) {
if (obj[i].type == 'text') {
$scope.fields.push(obj[i]);
} else {
structuredObj(obj[i])
}
}
};
structuredObj(inputs);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="myForm" novalidate>
<div ng-repeat="item in fields" class="form-group">
<input
name="item.name"
type="{{ item.type }}"
placeholder="{{ item.name }}"
ng-model="item.value"
required />
</div>
<button ng-disabled="myForm.$invalid">Submit</button>
</form>
</div>
<div ng-repeat="(key1, value1) in myPersonObj">
<div ng-repeat="(key, value) in value1">
<label>{{key}}</label>
<input type="text" name="" value="{{value}}">
</div>
</div>
var app = angular.module("test",[]);
app.controller("MainCtrl",function($scope){
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
]
}
];
$scope.person = [];
$scope.myPersonObj = [];
/*console.log($scope.keys(inputs));*/
$scope.checkIndex1 = function(arg, myPersonObj)
{
if (angular.isArray(arg) || angular.isObject(arg)) {
angular.forEach(arg, function (value, key) {
console.log(value);
if(angular.isObject(value) || angular.isArray(value))
{
$scope.checkIndex1(value, myPersonObj);
}
else
{
console.log("pushing");
myPersonObj.push(arg);
}
});
}
else
{
console.log("pushing1");
myPersonObj.push(arg);
}
}
$scope.checkIndex1($scope.inputs, $scope.myPersonObj);
console.log("myPersonObj :"+ JSON.stringify($scope.myPersonObj));
console.log($scope.inputs);
I am using Angular, Node.js, Sequelize/Postgres, and have a form (select options form). I am trying to make the option fields depend on each other, so for example when a particular first name is picked, only the corresponding last name is being shown in the other select options field. I don't really know how to do that, only found some similar examples but still don't quite understand how to do that when the values are fetched directly from the database and any help would be appreciated.
Angular factory:
app.factory('DoctorsFactory', function($http){
var DoctorsFactory={};
DoctorsFactory.fetchAll=function(){
return $http.get('/api/doctors')
.then(function(docs){
return docs.data;
})
}
return DoctorsFactory;
});
controller:
app.controller('AppointmenController', function ($scope, DoctorsFactory) {
$scope.doctors={};
DoctorsFactory.fetchAll()
.then(function(all){
console.log('bla', all)
$scope.docs=all;
})
});
HTML:
<div class="container">
<h2>Form control: select</h2>
<form ng-submit="searchForDoc(doctors)">
<div class="form-group">
<label for="sel1">Firstname</label>
<select class="form-control" id="sel1" ng-model="doctors.firstname">
<option ng-repeat="doc in docs">{{doc.firstname}}</option>
</select>
<br>
<label for="sel1">Lastname</label>
<select class="form-control" id="sel1" ng-model="doctors.lastname">
<option ng-repeat="doc in docs">{{doc.lastname}}</option>
</select>
<br>
<label for="sel1">Speciality</label>
<select class="form-control" id="sel1" ng-model="doctors.speciality">
<option ng-repeat="doc in docs">{{doc.speciality}}</option>
</select>
<br>
<label for="sel1">Department</label>
<select class="form-control" id="sel1" ng-model="doctors.department">
<option ng-repeat="doc in docs">{{doc.department}}</option>
</select>
<br>
<label for="sel1">School</label>
<select class="form-control" id="sel1" ng-model="doctors.school">
<option ng-repeat="doc in docs">{{doc.school}}</option>
</select>
<br>
</div>
<input type="submit">
</form>
</div>
route:
router.get('/', function(req,res,next){
Doctors.findAll({})
.then(function(alldoctors){
console.log(alldoctors)
res.send(alldoctors);
})
.catch(next);
})
database model:
var Sequelize = require('sequelize');
var db = require('../_db');
module.exports = db.define('doctors', {
firstname: {
type: Sequelize.STRING
},
lastname: {
type: Sequelize.STRING
},
speciality: {
type: Sequelize.STRING
},
department: {
type: Sequelize.STRING
},
gender: {
type: Sequelize.STRING
},
school: {
type: Sequelize.STRING
},
languages:{
type: Sequelize.STRING
}
});
I have a simple filter where I want to select a particular value and type and make other calls using that. Here is a close representation of what I have in my view (I am not using ng-repeat to create these radio buttons).
<form>
<label>
<input type="radio" name="ptf" ng-value="cntrl.filter.today_filter" ng-model="cntrl.filter.filter_value"> Today
</label>
<label>
<input type="radio" name="ptf" ng-value="cntrl.filter.hour_filter" ng-model="cntrl.filter.filter_value"> Last
</label>
<select ng-model="cntrl.filter.hours" ng-options="num for num in cntrl.filter.time_range"></select>
<label> hours</label>
<label>
<input type="radio" name="ptf" ng-value="cntrl.filter.date_filter" datepicker="" ng-model="cntrl.filter.filter_value">Select a Date
</label>
<button class="btn btn-info float-right" ng-click = "cntrl.refreshData()" >Update</button>
</form>
This basically gives me 3 options where I can select either today, or last n hours or another date. Here is the relevant code from my cntrl.
vm.filter = {
today_filter: {
type: 'today',
value: 1
},
date_filter: {
type: 'date',
value: 2
},
hour_filter: {
type: 'hours',
value: 3
},
hours: 8,
today: getFormattedDate(vm.current_date),
time_range: [],
filter_value: {
type: 'today',
value: 1
}
};
Now I have filter_value (ng-model) set as an object with type today and value 1. So I am expecting that by default my radio button with value of cntrl.filter.today_filter should be selected. And as I select other radio buttons, the filter_value object should update accordingly. Of course this is not happening. Is there some basic thing that is wrong here? Any pointers on how to fix this or maybe a different approach on this?
There are a few things wrong with your code:
You use the wrong aliasses for your controller in your view (spDashboardCntrl and cntrl)
Use the actual same object as the initial value instead of a new object that just looks the same.
For clarity, see the working example below.
angular.module('app',[])
.controller('myController', function() {
var vm = this;
vm.filter = {
today_filter: {
type: 'today',
value: 1
},
date_filter: {
type: 'date',
value: 2
},
hour_filter: {
type: 'hours',
value: 3
},
hours: 8,
today: '', //getFormattedDate(vm.current_date),
time_range: []
};
vm.filter.filter_value = vm.filter.today_filter;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController as vm">
<form>
<label>
<input type="radio" name="ptf" ng-value="vm.filter.today_filter" ng-model="vm.filter.filter_value">Today
</label>
<label>
<input type="radio" name="ptf" ng-value="vm.filter.hour_filter" ng-model="vm.filter.filter_value">Last
</label>
<select ng-model="vm.filter.hours" ng-options="num for num in vm.filter.time_range"></select>
<label>hours</label>
<label>
<input type="radio" name="ptf" ng-value="vm.filter.date_filter" datepicker="" ng-model="vm.filter.filter_value">Select a Date
</label>
<button class="btn btn-info float-right" ng-click="vm.refreshData()">Update</button>
</form>
{{vm.filter.filter_value}}
</div>
</div>
I'm working with a nested form group structure with Angular 2 beta "FormBuilder" and for the life of me I can't get values into the nested form group. It's weird because binding works just fine. I can send a "user" object to the form and it fills in all the values for the user and their address. But when sending the form value out (say, to an HttpPost), it looks just like the object below...
FWIW I'm following Mosh Hamedani's excellent Angluar 2 course on Udemy and have checked and double checked that the relevant code matches his here: https://github.com/mosh-hamedani/angular2-course
Perhaps what I need is to be told where else to look in my code?
Here's my form group as shown by placing {{ form.value | json }} at the end of my form:
{
"name": "Leanne Graham",
"email": "Sincere#april.biz",
"phone": "1-770-736-8031 x56442",
"address": {
"street": null,
"suite": null,
"city": null,
"zipcode": null
}
}
this is the constructor in my component:
constructor(
fb: FormBuilder,
private router: Router,
private usersService: UsersService,
private params: RouteParams
){
this.form = fb.group({
name: ['', Validators.required],
email: ['', EmailValidators.mustBeEmail], // I hadn't considered the obvious: if it doesn't exist it also doesn't qualify as email.
phone: [],
address: fb.group({
street: [],
suite: [],
city: [],
zipcode: []
})
});
}
This is the form in my template (truncated for brevity):
<div class="col-md-6 well">
<!--the "fieldset" element is needed for this kind of grouped layout.-->
<form [ngFormModel]="form" (ngSubmit)="save()">
<fieldset>
<legend>User</legend>
<div class="form-group">
<label>Name</label>
<input type="text" [(ngModel)]="user.name" ngControl="name" #name="ngForm" class="form-control">
<div class="alert alert-danger" *ngIf="name.errors && name.touched">
The user name is required.
</div>
</div>
*** Email and Phone similar ***
</fieldset>
<fieldset ngControlGroup="address">
<legend>Address</legend>
<div class="form-group">
<label>Street</label>
<input type="text" [(ngModel)]="user.address.street" ng-control="street" class="form-control">
</div>
*** suite, city, and zip similar ***
</fieldset>
{{ form.value | json }}
<button [disabled]="!form.valid" class="btn btn-primary" type="submit">Save</button>
</form>
</div>
ng-control="street"
should be
ngControl="street"
like you did with name