I have an event.controller.js and event.view.html
In the controller I have event and guests,
event is the form of multiple models and guests is 1 model with an array that I can pass more values too.
I have localStorage for events to save the form but guests array doesn't get passed into the form because they are seperated even though they're part of the same controller.
function EventController($location, UserService, EventService, $rootScope, $http, FlashService) {
var vm = this;
vm.guests = [];
vm.addGuest = function () {
vm.guests.push(vm.newGuest);
}
vm.removeGuest = function (guest) {
var index = vm.guests.indexOf(guest);
vm.guests.splice(index, 1);
}
vm.event = event;
function event() {
vm.dataLoading = true;
EventService.Create(vm.events)
.then(function (response) {
if (response.success) {
FlashService.Success('Event created successful', true);
$location.path('/events');
} else {
FlashService.Error(response.message);
vm.dataLoading = false;
}
});
}
my event.view.html looks like
<form name="form" ng-submit="vm.event()" role="form">
<!--All my event input fields-->
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Create</button>
Cancel
</div>
</form>
<form name="form" ng-submit="vm.guest()" role="form">
<div class="form-actions">
<button type="submit" ng-disabled="guestform.$invalid || vm.dataLoading" ng-click="vm.addGuest()" class="btn btn-primary">Add Guest</button>
</div>
<div ng-repeat="guest in vm.guests track by $index" class="col-sm-6">
{{guest}} - <a class="btn" ng-click="vm.removeGuest(guest)">Delete</a>
</div>
</form>
different forms submit to the same eventcontroller but are different model namespaces, how would I get a vm.events.guest array that is equal to the vm.guests after I add to it from the vm.addGuest() method?
Related
I have a form with different text fields and some buttons. I want for every press of a button to execute a different operations, but using the the same function of ng-submit(). For example I want to implement CRUD operations on a database, and based on the data I get from the form to execute another operations. Based on the information from another post from the site I managed to do this:
<form name="formUser" ng-submit="cruduser()" role="form">
// I didn't put the text fields because are irrelevant for this problem
<div class="form-actions">
<button type="submit" ng-click="addButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Add</button>
</div>
<br/>
<div class="form-actions">
<button type="submit" ng-click="readButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Read</button>
</div>
<br/>
<div class="form-actions">
<button type="submit" ng-click="updateButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Update</button>
</div>
<br/>
<div class="form-actions">
<button type="submit" ng-click="deleteButton=true" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Delete</button>
</div>
</div>
This is my .js file:
'use strict';
angular.module('admin')
.controller('AdminController',
['$scope', '$rootScope', '$location', 'AdminService',
function ($scope, $rootScope, $location, AdminService) {
$scope.cruduser = function() {
this.addButton = false;
this.readButton = false;
this.updateButton = false;
this.deleteButton = false;
if(this.addButton) {
console.log('Add');
}
if(this.readButton) {
console.log('Read');
}
if(this.updateButton) {
console.log('Update');
}
if(this.deleteButton) {
console.log('Delete');
}
};
$scope.redirect = function() {
session.sessionValue = ' ';
window.location = "/#/login";
}
}]);
The problem is that after I initialize the buttons with "false", they remain stuck with that value.
You can pass the type of operation that you want in your cruduserfunction on click of the buttons like this:
<button ng-click = "cruduser('add')"></button>
Then in the cruduser function in the controller you can check for the passed operation like this:
$scope.cruduser = function(crudOp) {
if (crudOp === 'add') {
//do something
}
}
So, I am creating a web app, where one page I have a user list and on the second page, I have the users details page. On the second page, I have a confirm button where I want to remove that user when the "Confirm" button is clicked with a 200 Status code. However, I am getting a DELETE : 405 (Method Not Allowed). So, here is my code down below. Please tell me or help me fix this problem. Thank you in advance.
Here is my code.
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<button class="btn btn-primary" ng-click="doDelete(id)">Confirm</button>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
</fieldset>
</form>
</div>
</div>
</div>
Services
app.factory('people', function ($http) {
var service = {};
service.getUserInfo = function () {
return $http.get('https://api-dev.mysite.io/admin/v1/unconfirmed_lawyers');
};
service.confirmUser = function (lawyerId) {
return $http.put('https://api-dev.mysite.io/admin/v1/lawyers/{lawyerId}/confirm');
};
return service;
});
LawyerController
app.controller('LawyerController', ['$scope', 'people', '$routeParams',
function ($scope, people, $routeParams) {
$scope.lawyerId = $routeParams.id;
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
});
}]);
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, people, $http) {
if (!isConfirmed) {
people.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
}, function (error) {
console.log(error)
});
}
});
App.js
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1);
location.href = '#/lawyer';
};
If you changed your HTML, so you passed the person instead.
<button class="btn btn-primary" ng-click="doDelete(person)">Confirm</button>
You can use this to find the index within the lawyers, then remove it.
$scope.doDelete = function(lawyer) {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
$scope.userInfo.lawyers.splice(index, 1)
};
The issue is your are using $http.delete which performs an HTTP Delete request. This doesn't sound like something you intended.
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>
I have 3 radio buttons in a bootstrap modal and I want only 2 of them to be required in order to submit the form. I created a requiredCheck() function that's using a jQuery implementation so I'd rather not use this. What is the best way to disable the required attribute for one radio button, when using AngularJS?
HTML
<form name="jawn">
<div class="modal-header">
<h3 class="modal-title">Jawn</h3>
</div><!-- /modal-header -->
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<label for="optionsRadios">
<input type="radio" ng-model="$parent.data.status" name="optionsRadios" ng-value="item.id" required/ ng-click="requiredCheck()"> {{item.name}}
</label>
</li>
</ul>
<h4>Comment</h4>
<textarea ng-class="{error: thing.comment.$dirty && thing.comment.$invalid}" type="text" rows="3" cols="64" ng-model="data.comment" ng-minlength="4" ng-required></textarea>
<span class="error" ng-show="thing.comment.$error.required">required</span>
</div><!-- /modal-body-->
<div class="modal-footer">
<button type="submit" class="btn btn-warning" ng-click="ok()" ng-disabled="thing.$invalid">Part Jawn</button>
<button type="button" ng-click="cancel()" class="btn btn-default">Cancel</button>
</div>
</form>
JavaScript
angular.module('app')
.controller('ModalController', function($scope, $modalInstance, $timeout) {
'use strict';
$scope.item = 0;
$scope.items = [
"Zero": 0,
"Uno": 1,
"Dos": 2
];
$scope.requiredCheck = function () {
var $btnWarning = $('.btn-warning');
var $textarea = $('textarea');
$timeout(function() {
if($scope.data.status === item.Dos) {
$btnWarning.removeAttr('disabled');
$textarea.removeAttr('required');
} else if ($scope.data.status === 3) {
$btnWarning.prop('disabled',true);
$textarea.prop('required', true);
} else if ($scope.data.status === 3) {
$btnWarning.prop('disabled',true);
$textarea.prop('required', true);
}
},100);
};
$scope.ok = function () {
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
$modalInstance.close();
};
});
You should use angualrjs approach. As you have already specified ngRequired set true/false from controller.
From DOCs
ngRequired: Sets required attribute if set to true
HTML
<textarea ng-model="data.comment" ng-required="textRequired"></textarea>
Script
$scope.requiredCheck = function () {
if(condition){
$scope.textRequired = false;
}else{
$scope.textRequired = true;
}
};
Note: I have simplified the answer
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();})
}