i ask this question ago but don't get answer. i have a form that by filling it create json object and post to server.this form repeat in several time.
The data entry forms can be repeated several times.
<div ng-repeat="office in offices">
<input type="text" ng-model="officeName">
<input type="text" ng-model="office.employee">
<input type="text" ng-model="office.employee">
<button ng-click="addOffice()">Add New Office</button>
</div>
suppose my objects are
public class FormData{
private List<Data> all;
}
public class Data{
private String officeName;
private List<Employee> list;
}
public class Employee{
private String name;
}
how create json objects and bind data that get from form bind to this objects?
And how create form entry data?(how set ng-model)
You can do something like this:
var app = angular.module('app', ['ngMockE2E']);
app.controller('myController', function($scope, $http) {
$scope.offices = [];
$scope.addOffice = function() {
$scope.offices.push({
employees: []
});
};
$scope.addEmployee = function(office) {
office.employees.push({});
};
$scope.submitOffices = function() {
$http.post('/offices', $scope.offices)
.success(function() {
// Handle success.
}).error(function() {
// Handle error.
});
};
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular-mocks.js"></script>
<div ng-app='app' ng-controller='myController'>
<button ng-click="addOffice()">Add New Office</button>
<div ng-repeat="office in offices" ng-if="offices">
<form name="officesForm" novalidate ng-submit="submitOffices()">
Company Name:
<input type="text" ng-model="office.name">
<div>
Employees:
<ng-form name="employeForm{{$index}}" ng-repeat="employee in office.employees">
<div>
<input type="text" ng-model="employee.name">
</div>
</ng-form>
<button type="button" ng-click="addEmployee(office)">Add Employee</button>
</div>
<button type="submit">submit</button>
</form>
</div>
<pre>{{ offices | json }}</pre>
</div>
The sandboxed iframe prevents it from posting so here it is on plunker.
http://plnkr.co/edit/2eGVa3tg3TtIhFXNpUGI?p=preview
Related
Long story short, it works if I change < to = here:
const rtmNav = {
bindings: {
from:'<',
to:'<',
submit: '&'
},
controller: angular.noop,
templateUrl: require('./rtmNav.html')
}
export default rtmNav;
This is the controller where dataa object is defined:
class DemandCtrl {
constructor(ChartDataService) {
this.ChartDataService = ChartDataService;
debugger;
this.dataa = {
from: '10/01/2017',
to: '10/03/2017'
};
}
$onInit() {
getData.call(null, this);
}
update() {
getData.call(null, this);
}
}
The component looks like this:
<div class="rtm-nav">
<div ng-app>
<form ng-submit="$ctrl.submit()">
<label>From:
<input type="text" name="input" ng-model="$ctrl.from">
</label>
<label>To:
<input type="text" name="input" ng-model="$ctrl.to">
</label>
<input type="submit" id="submit" value="Apply" />
</form>
</div>
</div>
And the html page like this:
<div class="demand page">
<rtm-header title="Demand" icon="fa fa-line-chart" link=true></rtm-header>
<rtm-nav from="$ctrl.dataa.from", to="$ctrl.dataa.to", submit="$ctrl.update()">
</rtm-nav>
<div id="chart" class="demand-chart">
</div>
</div>
When I first run the application, it shows the chart between the hardcoded values (10/01/2017 and 10/03/2017). If it is made as two-way data binding, if I change those values and click on apply it will re-render the chart with the new data.
My constraint is do to it one-way data binding.
I don't know how to do it, show I send the new parameters in update() or should I add them somehow in the component?
I'm trying to apply the autocomplete feature in my angular project, but it does not works.
Here code -
<!-- Start ignoring BootLintBear -->
<form class="navbar-form navbar-left">
<!-- Stop ignoring BootLintBear -->
<div class="input-group" id="nav-group">
<input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery($event)"
[(ngModel)]="searchdata.query">
<div id="output"></div>
<script>
function suggestMe(data) {
document.getElementById('output').innerHTML = data;
}
var storeData = '';
document.getElementById('nav-input').onkeyup = function() {
if(storeData!== ''){
document.body.removeChild(storeData);
}
var textBox = document.getElementById('nav-input').value;
storeData = document.createElement('script');
storeData.src = 'http://en.wikipedia.org/w/api.php?action=opensearch&limit=10&format=json&callback=suggestMe&search=' + textBox;
document.body.appendChild(storeData);
};
</script>
<div class="input-group-btn">
<button class="btn btn-default" id="nav-button" type="submit" (click)="submit()">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
Suggestions are welcomed : )
Instead of mixing pure JavaScript with Typescript, why not do it in full Typescript ? Try this way or adapt it to your need. First set up an observable stream
data: Observable<any>;
private searchTerms = new Subject<string>();
onquery(term: string): void {
this.searchTerms.next(term);
}
Next, set up the search feature
ngOnInit(): void {
this.data = this.searchTerms
.debounceTime(300) // pause in events
.distinctUntilChanged() // ignore if search term not changed
.switchMap(term => term // switch to new observable each time
//http service to retrieve your data
? this.searchService.search(term)
: Observable.of<any>([])
)
.catch(error => {
console.log(error);
});
}
Template :
<input #input type="text" name="query" class="form-control" id="nav-input" (keyup)="onquery(input.value)">
<div id="output">
<div *ngFor="let item of (data | async)">{{ item }}</div>
</div>
I'm trying to push some info to an array and show it with ng-repeat but for some reason it's not working
This is my controller:
(function () {
'use strict';
angular
.module('app.article')
.controller('Article', Article);
function Article($location) {
var vm = this;
vm.comments = [];
vm.addComment = addComment;
function addComment() {
vm.comments.push(vm.newComment);
vm.newComment = {};
}
}
})();
Here's the plunkr: https://plnkr.co/edit/jPOJDXoG1vgNfsDzyJAD?p=preview
Thanks for the help
for your controller you are using a controller As syntax so you will have to refer to scope variables with a prefix of vm.
<div ng-controller="Article as vm">
<form ng-submit="vm.addComment()">
<textarea placeholder="Sign in to share your thoughts." ng-model="vm.newComment.comment"></textarea>
<input type="text" class="form-control" ng-model="vm.newComment.user">
<input type="submit" class="btn btn-primary" value="Post">
</form>
<ul>
<li ng-repeat="comment in vm.comments">{{comment.user}} - {{comment.comment}}</li>
</ul>
</div>
Also in your controller you have to initialize a newComment object
function Article($location) {
var vm = this;
vm.comments = [];
vm.addComment = addComment;
vm.newComment = {user: '', comment: ''}
function addComment() {
vm.comments.push(vm.newComment);
vm.newComment = {};
}
}
Updated Plunker
<div ng-controller="Article as vm">
<form ng-submit="vm.addComment()">
<textarea placeholder="Sign in to share your thoughts." ng-model="vm.newComment.comment"></textarea>
<input type="text" class="form-control" ng-model="vm.newComment.user">
<input type="submit" class="btn btn-primary" value="Post">
</form>
<ul>
<li ng-repeat="comment in vm.comments">{{comment.user}} - {{comment.comment}}</li>
</ul>
</div>
Here is the updated plunkr
https://plnkr.co/edit/HK4WIYCF6poMXncBU9Uk?p=preview
I am currently facing a problem, which has to do with views. I am making an app, which allows for users to create polls. When the poll that a user creates is submitted, I call a POST route to store it:
$scope.userVal = Auth.getCurrentUser();
$http.post('/api/users/update' + $scope.userVal._id, {polls: $scope.polls}).success(function(res){
//console.log("res: ", res);
});
Essentially, I get the user info,and use his id to store the new poll in a schema-defined value called polls.
Now, when a user clicks a button, I display the polls that were created via a ng-view:
$scope.pollView= function(){
$scope.userVal2 = Auth.getCurrentUser();
$scope.userVal2 = $scope.userVal2.polls;
$scope.button = true;
};
In the html, I simply iterate over $scope.userVal2. My problem comes when I try to view a newly created poll. The poll does not initially show up, but if I refresh the page, then it shows up. Is there any reason for this? Does this have to do with the async calls?
Any help would be appreciated!
edit:
Controller:
'use strict';
angular.module('voteApp')
.controller('WallCtrl', function ($scope, $http, Auth) {
$scope.items = [];
$scope.title;
$scope.button = false; //set default to the new poll
$scope.polls = [];
$scope.items.push({id:1, upvotes:0, text:""});
$scope.items.push({id:2, upvotes:0, text:""});
$scope.addOptions = function(){
$scope.items.push({id:$scope.items.length +1, upvotes:0, text:""});
};
$scope.process = function(name, values){
$scope.polls.push({title:name, options:values});
$scope.title = ""; //reset the values for the next poll
$scope.items = [];
$scope.items.push({id:1, upvotes:0, text:""});
$scope.items.push({id:2, upvotes:0, text:""});
$scope.userVal = Auth.getCurrentUser();
$http.post('/api/users/update' + $scope.userVal._id, {polls: $scope.polls}).success(function(res){
//console.log("res: ", res);
});
};
$scope.newView= function(){
$scope.button = false;
};
$scope.pollView= function(){
$scope.userVal2 = Auth.getCurrentUser().polls
$scope.button = true;
};
$scope.delete = function(val){
$scope.polls = $scope.polls.filter(function(returnableObjects){
return returnableObjects.title !== val.title;
});
};
});
html:
<div ng-include="'components/navbar/navbar.html'"></div>
<header class="hero-unit" id="banner">
<div class="container">
<h1>Dashboard</h1>
<p class="lead">What would you like to do today?</p>
<button ng-click="newView()" type="button" class="btn btn-lg newpoll">New Poll</button>
<button ng-click="pollView()"type="button" class="btn btn-lg mypolls">My Polls</button>
</div>
</header>
<div ng-show= "!button">
<form name="form" ng-submit="process(title, items)">
<h2 class="col-md-12 text-center">New Poll</h1>
<h5 class="col-md-12 text-center">Name your poll.</h1>
<input name="pollname" ng-model="title"type="text" class="form-control input_width" placeholder="Poll Name" required>
<br>
<h5 class="col-md-12 text-center">Options</h1>
<div ng-repeat="item in items">
<p>
<input name = "{{item.id}}" ng-model="item.text" type="text" class="form-control input_width" placeholder="Option {{item.id}}" required>
</p>
</div>
<br>
<div class="text-center">
<button type="button"ng-click="addOptions()" class="btn options" formnovalidate>More Options</button>
</div>
<br>
<div class="text-center">
<button type="submit" class="btn button" validate>Submit</button>
</div>
</form>
</div>
<div ng-show="button" >
<br>
<div ng-repeat="poll in userVal2">
<div class="polldeco">
{{poll[0].title}}
<button class="btn buttondeco" ng-click="delete(poll)">Delete</button>
</div>
</div>
</div>
Some ideas:
$scope.userVal2 = Auth.getCurrentUser().polls is using the old version prior to the creation of a new poll? Maybe this could be changed to something like Auth.getCurrentUser().then(...). Either way, ensure that the call to getCurrentUser() is returning new data.
ng-view is cached. When a template is initially requested, it gets stored in the $templateCache. If this template is rendered on the backend for display in as a partial (eg: ng-view) and it is not static content, then you will have to invalidate the cache to update the view.
Consider having the backend return the new poll from $http.post('/api/users/update' ...) and adding it to the list used by ng-repeat. Something like:
$scope.process = function(name, values) {
$scope.polls.push({title:name, options:values});
...
$http.post('/api/users/update' + $scope.userVal._id, {polls: $scope.polls}).success(function(poll){
$scope.polls.push(poll);
});
};
...
<div ng-repeat="poll in polls">
<div class="polldeco">
{{poll[0].title}}
<button class="btn buttondeco" ng-click="delete(poll)">Delete</button>
</div>
</div>
Can't access form variable from my controller, when i try to access it by $scope.locationForm i've got 'undefined', but when i call console.log($scope) i can see in console there have loactionForm.
My HTML code
<div ng-controller="LocationsController as ctrl">
<form class="form-inline" name="locationForm">
<div class="form-group">
<!-- <div class="input-group"> -->
<label for="location-name">Название населенного пункта</label>
<input required
name="name"
ng-model="ctrl.location.name" type="text" class="form-control" id="location-name" placeholder="Название населенного пункта">
<label for="location-name">Район</label>
<select required
name="region_id"
ng-model="ctrl.location.region_id"
ng-options="region.id as region.name for region in ctrl.regions" class="form-control" placeholder="Название района"></select>
<input ng-click="ctrl.save()"
ng-disabled="locationForm.$invalid" type="submit" class="btn btn-default" value="Cохранить">
<a class="btn btn-default" ng-click="ctrl.reset()" ng-show="locationForm.$dirty">Сброс</a>
<!-- </div> -->
</div>
</form>
My Controller code:
function LocationsController($scope, Location, Region, $q) {
var lc = this,
l_index;
lc.form ={};
lc.regions = lc.locations = [];
lc.regions = Region.query();
lc.regions.$promise.then(function(data) {
lc.locations = Location.query();
});
lc.getRegion = function (id) {
return lc.regions.filter(function(obj) {
return obj.id == id;
})[0].name;
};
console.log($scope);
// console.log($scope.locationForm);
lc.reset = function () {
lc.location = new Location;
}
lc.reset();
};
The problem is when the LocationsController is initialized the form element is not yet compiled. So one possible hack is to use a timeout like
function LocationsController($scope, Location, Region, $q, $timeout) {
//then later
$timeout(function(){lc.reset();})
}