Cannot read property '$invalid' of undefined - angularjs

I am creating a statistics page using angular.
When I submit the form it throws the error Cannot read property '$invalid' of undefined.
Here is the html:
<form name="statsForm" ng-submit="quoteRequestsKpi()" novalidate>
<div class="row">
<div class="col-lg-5">
<div class="form-group" show-errors="{ showSuccess: true }">
<label for="month">Month</label>
<select name="month" id="month" class="form-control" required="required" ng-model="statsIn.month">
<option value="0">January</option>
<option value="1">February</option>
...
</select>
</div>
</div>
<div class="col-lg-5">
<div class="form-group" show-errors="{ showSuccess: true }">
<label for="year">Year</label>
<select name="year" id="year" class="form-control" required="required" ng-model="statsIn.year">
<option value="2016">2016</option>
<option value="2017">2017</option>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label> </label>
<input type="submit" class="btn btn-primary form-control" value="go" />
</div>
</div>
And here is the js code :
controllers.controller('StatsController', [
'$scope', 'growl', 'appService',
function($scope, growl, appService) {
var logger = log4javascript.getLogger('Stats');
logger.debug('StatsController');
/**
*/
$scope.statsIn = {
month : null,
year : '2017'
};
/**
*/
$scope.$on(EVENT_CURRENT_USER_SUCCESS, function() {
logger.debug(EVENT_CURRENT_USER_SUCCESS);
$scope.init();
});
/**
*/
$scope.quoteRequestsKpi = function() {
logger.debug('quoteRequestsKpi');
$scope.$broadcast('show-errors-check-validity');
if ($scope.statsForm.$invalid) {
return;
}
appService.quoteRequestsKpi($scope.kpiIn).then(function(data) {
if (data.status == SUCCESS) {
$scope.quoteRequestKpis = data.quoteRequestKpis;
} else {
logger.warn('quoteRequestsKpi: ' + JSON.stringify(data));
}
});
}
$scope.ensureUserIsAuthenticated();
}]);
Does anyone know why I am getting an error ?

Because your form is undefined inside your controller. You have to create a reference to the form in your controller.
This could be accomplished either by using controllerAs syntax:
e.g.
In the view:
<div ng-controller="StatsController as vm">
<form name="vm.statsForm">
<!--Input Fields...-->
</form>
</div>
Controller:
var vm = this;
vm.statsForm// This is a reference to your form.
Or if you wish to inject $scope in the controller, then the answer of how to access your form can be found here.
Here's a working plunker.

Related

Get ng-model with index from ng-repeat in controller

I can't find the answer to this over google so i post my question here :
I need to send an http.post request to a php file based on inputs value that I get from a ng-model directive in my view but its located inside a ng-repeat. I must use $index because its from a form that repeat for each line in my database.In simple word it's for update my data base but just the line i'm interested in
But I keep getting the following error
TypeError: Cannot read property '0' of undefined
because my ng-model seems to have another name. Can you explain me how to name a ng-model value in controller with the index so it match the one one the view. Thank's in advance.
Here my code :
<ul>
<li class="err" ng-repeat="error in admin.errors"> {{error}} </li>
</ul>
<ul>
<li class="info" ng-repeat="msg in admin.msgs"> {{msg}} </li>
</ul>
<form class="form-inline" ng-repeat="data in admin.datas track by $index" novalidate ng-submit="admin.modify($index)">
<div class="form-group">
<div class="col-10">
<input class="form-control" type="text" ng-value="data.id" ng-model="admin.id[$index]" id="id">
</div>
</div>
<div class="form-group">
<div class="col-10">
<input class="form-control" type="text" ng-value="data.nom" ng-model="admin.nom[$index]" id="nom">
</div>
</div>
<div class="form-group">
<div class="col-10">
<input class="form-control" type="text" ng-value="data.prenom" ng-model="admin.prenom[$index]" id="prenom">
</div>
</div>
<div class="form-group">
<select class="form-control" id="structure" ng-value="data.structure" ng-model="admin.structure[$index]">
<option value="1">Structure 1</option>
<option value="2">Structure 2</option>
<option value="3">Structure 3</option>
<option value="4">Structure 4</option>
<option value="5">Structure 5</option>
</select>
</div>
<div class="form-group">
<div class="col-10">
<input class="form-control" type="text" id="fonction" ng-value="data.fonction" ng-model="admin.fonction[$index]">
</div>
</div>
<div class="form-group">
<textarea class="form-control" id="message" rows="1" ng-value="data.message" ng-model="admin.message[$index]"></textarea>
</div>
<button type="submit" class="btn btn-primary">Modifier</button>
</form>
my controller :
(function() {
'use strict';
angular
.module('AA')
.controller('adminCtrl', adminCtrl);
function adminCtrl($http){
const admin = this;
/* Parti recup*/
admin.datas = [];
admin.getMsg = function(){
$http.get('/dylan/ActeurAvenir/libs/read.php').then(function(response) {
admin.datas = response.data;
})
}
admin.getMsg();
/* Parti post*/
admin.msgs = [];
admin.errors = [];
admin.modify = function($index){
$http.post('/dylan/ActeurAvenir/libs/modify.php', {
'id' : admin.id[$index],
'nom' : admin.nom[$index],
'prenom' : admin.prenom[$index],
'structure' : admin.structure[$index],
'fonction' : admin.fonction[$index],
'message' : admin.message[$index]
}
).then(function(result) {
if (result.data.msg != '')
{
admin.msgs.push(result.data.msg);
}
else
{
admin.errors.push(result.data.error);
}
})
}
};
adminCtrl.$inject = ['$http'];
})();
Here
$http.post('/dylan/ActeurAvenir/libs/modify.php', {
'id' : admin.id[$index],
'nom' : admin.nom[$index],
'prenom' : admin.prenom[$index],
'structure' : admin.structure[$index],
'fonction' : admin.fonction[$index],
'message' : admin.message[$index]
}
I think you need to access admin.datas[$index].id, admin.datas[$index].nom and so on, since admin.datas is the array
about your ng-model
you should be binding against
ng-model="data.id" which comes from your ng-repeat rather than using admin.datas[$index].id
It is less code, its more declarative, and if you add a filter your code will stop working.
Ok so I find the answer thanks to Gonzalo answer and my own investigation, what You need to do here is to change the http.post() value so it's like
'id' : admin.datas[$index].id, admin.datas[$index].nom and so on
AND change the ng-model in the view so its like :
ng-model="admin.datas[$index].id"
Hope this will help someone in the future.

Submitting multiple check-box selection in ASP.NET MVC form with Angular JS

I have a form with textboxes, dropdownlists and checkboxes. I have the challenge of submitting several checkbox items into the database. The data did submit but it only submits the last checked item on the form.
Here's is my UI
<div class="block type-3">
<div class="container">
<div class="row post animated fadeInUp">
<div class="col-xs-12 form-block">
<div ng-controller="tutorequestController">
<form name="tutrequestform" novalidate>
<div class="form-text">Required fields are <span class="text-blue">*</span>. Fill out the form and we'll contact you soon</div>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.firstname" name="firstname" type="text" class="form-input" placeholder="Firstname *" required />
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.lastname" name="lastname" type="text" class="form-input" placeholder="Lastname *" required />
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.phonenumber" name="phonenumber" type="number" class="form-input" placeholder="Phone Number *" required />
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.phonenumber2" name="phonenumber2" type="number" class="form-input" placeholder="Re-type Phone Number *" required />
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.emailaddress" name="emailaddress" type="email" class="form-input" placeholder="Email Address *" required />
</div>
<div>
<div ng-controller="stateLGAController">
<div class="col-xs-12 col-sm-6">
<!--<select ng-change="GetStateLgas()" ng-options="moreState as moreState.state1 for moreState in moreStates track by moreState.state_id" ng-model="select" class="form-input"><option>Select Your State</option></select>-->
<select ng-model="tutorRequest.state_id" ng-change="GetStateLgasByid(tutorRequest.state_id)"
ng-options="moreState.state_id as moreState.state1 for moreState in moreStates" class="form-input">
<option>Select Your State</option>
</select><!---->
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.lga_id"
ng-options="lga.lga_id as lga.local_govt for lga in stateLGA" class="form-input">
<option>Select Your L.G.A</option>
</select>
</div>
</div>
</div>
<div class="col-xs-12">
<textarea ng-model="tutorRequest.address" class="form-input" name="address" placeholder="House Address *" required></textarea>
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.numofchild" name="numofchild" class="form-input">
<option value='Select-Number-of-Child-for-Tutor'>Select number of Child/ren for Tutor</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.classrangeandage" class="form-input" name="classrangeandage" type="text" required placeholder="Class range of each child and age respectively *" />
</div>
<div class="col-xs-12 form-text">
<span class="text-blue">What subject would the tutor teach? Tick appropriate subject below.</span>
</div>
<div ng-app="app" ng-controller="subjectController">
<div ng-repeat="sub in tutorRequest.tutorsubject" class="col-xs-12 col-sm-4">
<div class="chBoxPad">
<input ng-model="tutorRequest.tutorsubject[$index].checked" type="checkbox" id="{{sub.sub_id}}" name="{{sub.subject1+'_'+$index}}" ng-change="updateChecked()" />
<label for="{{sub.sub_id}}"><span></span>{{sub.subject1}}</label>
</div>
</div>
</div>
<div class="col-xs-12">
<select ng-model="tutorRequest.preferredsexoftutor" name="sex" id="sex" class="form-input">
<option value="preferredsexoftutor" selected="selected">Preferred Sex of Tutor</option>
<option value="any">Any</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.childcurrentschool" name="childcurrentschool" type="text" class="form-input" placeholder="Current School of Child *" required />
</div>
<div class="col-xs-12">
<select ng-model="tutorRequest.schoolcurriculum" name="schoolcurriculum" id="curi" class="form-input">
<option value="">What curriculum does the school use</option>
<option value="Not Sure">Not Sure</option>
<option value="British Curriculum">British Curriculum</option>
<option value="American Curriculum">American Curriculm</option>
<option value="Nigerian Curriculum">Nigerian Curriculum</option>
<option value="Combination of British and Nigerian">Combination of British and Nigerian</option>
<option value="Question doesnt apply to me">Question doesn't apply to me</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.urgencyoftutor" name="urgencyoftutor" id="urgencyoftutor" class="form-input">
<option value="">Urgency of tutor</option>
<option value="Urgently" selected="selected">Urgently</option>
<option value="In 1 Week">In a Week</option>
<option value="In 2 Weeks">In 2 Weeks</option>
<option value="In a Month">In a Month</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.calltime" name="calltime" id="calltime" class="form-input">
<option value="" selected="selected">What time of the day would you like to be called</option>
<option value="Anytime">Anytime</option>
<option value="8 to 12">Morning - between 8am and 12noon</option>
<option value="12 to 3">Afternoon - between 12noon to 3pm</option>
<option value=" 3 to 6">Evening - between 3pm to 6pm</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.frequencyoftutor" name="frequencyoftutor" id="frequencyoftutor" class="form-input">
<option value="">How many times a week would you like the tutor to come</option>
<option value="1">Once a week</option>
<option value="2">2 times a week</option>
<option value="3">3 times a week</option>
<option value="4">4 times a week</option>
<option value="5">5 times a week</option>
<option value="6">6 times a week</option>
<option value="7">7 times a week</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.tutorhrs" name="tutorhrs" id="tutorhrs" class="form-input">
<option value="">How many hours per day should tutoring hold</option>
<option value="1" selected="selected">1 hr</option>
<option value="2">2 hrs</option>
<option value="3">3 hrs</option>
<option value="4">4 hrs</option>
<option value="5">5 hrs</option>
<option value="6">6 hrs</option>
<option value="7">7 hrs</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<input ng-model="tutorRequest.goal" name="goal" type="text" class="form-input" placeholder="Specific goal for tutoring session" required />
</div>
<div class="col-xs-12 col-sm-6">
<select ng-model="tutorRequest.howdidyouhearaboutus" name="howdidyouhearaboutus" class="form-input">
<option value="">How did you hear about us</option>
<option value="Google" selected="selected">Google</option>
<option value="Facebook">Facebook</option>
<option value="I got an SMS from Prepschool">I got an SMS from Prepschool</option>
<option value="Twitter">Twitter</option>
<option value="Nairaland">Nairaland</option>
<option value="I saw a flyer">I saw a flyer</option>
<option value="Prepschool Brochure">Prepschool Brochure</option>
<option value="A friend / member of household">A friend / member of household</option>
<option value="Other">Other</option>
</select>
</div>
</div>
<div class="col-xs-12">
<span class="button">
<button type="submit" class="submit" ng-click="CreateTutRequest(tutorRequest, tutrequestform.$valid)">Submit Request</button>
</span>
<!--<td><input type="submit" ng-click="CreateEmployee(Emp, myForm.$valid)" value="Create" /></td>
<td><input type="submit" ng-click="UpdateEmployee(Emp)" value="Update" /></td>-->
<span class="success"></span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
And here's the a partial graphical representation of the UI in image format.
And here's my angularJs controller for the page.
myApp.factory('crudServiceTutorrequest', function ($http) {
// Create an object and start adding methods to the object.
crudTutRObj = {};
// Add create method to the crudTutRObj
crudTutRObj.getAll = function () {
var tutorRequests;
tutorRequests = $http({ method: 'GET', url: '/Tutorrequest/Index' }).
then(function (response) {
return response.data;
});
return tutorRequests;
}
crudTutRObj.getStates = function () {
var ddlStates;
ddlStates = $http({ method: 'GET', url: '/States/Index' }).
then(function (response) {
return response.data;
});
return ddlStates;
}
crudTutRObj.getSubject = function () {
var Subjects;
Subjects = $http({ method: 'GET', url: '/Subject/Index' }).
then(function (response) {
return response.data;
});
return Subjects;
}
crudTutRObj.createTutRequest = function (tutRequest) {
var tutorRequest;
tutorRequest = $http({ method: 'POST', url: '/Tutorrequest/Create', data: tutRequest }).
then(function (response) {
return response.data;
});
return tutorRequest;
}
crudTutRObj.getById = function (id) { }
crudTutRObj.update = function (fms) { }
crudTutRObj.deleteById = function (id) { }
return crudTutRObj;
});
myApp.controller('tutorequestController', function ($scope, crudServiceTutorrequest) {
// Get all tutorRequests
//crudServiceTutorrequest.getAll().then(function (result) {
// $scope.tutorRequests = result;
//})
// Get data for states to populate the states dropdownlist
crudServiceTutorrequest.getStates().then(function (result) {
$scope.moreStates = result;
})
// Submit the form with the create function
$scope.CreateTutRequest = function (tutorRequest) {
crudServiceTutorrequest.createTutRequest(tutorRequest).then(function (result) {
$scope.Msg = "Tutor Request has been submitted successfully!";
});
}
});
myApp.controller('stateLGAController', function ($scope, $http) {
$scope.GetStateLgas = function () {
$http({ method: 'Get', url: '/StateLGA/Index' })
.then(function (response) {
$scope.stateLGA = response.data;
});
};
$scope.GetStateLgasByid = function (state_id) {
$http({ method: 'Get', url: '/StateLGA/GetlgaByStateid/' + state_id })
.then(function (response) {
$scope.stateLGA = response.data;
});
};
});
angular.module("app", []).controller('subjectController', ['$scope', function ($scope, crudServiceTutorrequest) {
var subjects;
subjects = crudServiceTutorrequest.getSubject().then(function (result) {
$scope.subjects = result;
})
$scope.tutorRequest = {
tutorsubject: subjects
};
angular.forEach($scope.subjects, function (subject) {
var sub = angular.merge({ checked: false }, subject);
$scope.tutorRequest.tutorsubject.push(sub);
});
$scope.allSubjectChecked = [];
$scope.updateChecked = function () {
console.log($scope.tutorRequest.tutorsubject);
$scope.allSubjectChecked = [];
angular.forEach($scope.tutorRequest.tutorsubject, function (sub) {
if (sub.checked) {
$scope.allSubjectChecked.push(sub);
}
});
}
}]);
And finally, the js file is routes all the pages to the ng-view
var myApp = angular.module("myApp", ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider.when('/Department', {
templateUrl: 'Templates/Admin/Department/Department.html',
controller: 'departmentController'
});
$routeProvider.when('/Employee', {
templateUrl: 'Templates/Admin/Employee/Employee.html',
controller: 'employeeController'
});
$routeProvider.when('/Aboutus', {
templateUrl: 'Templates/User/Aboutus/Aboutus.html',
controller: ''
});
$routeProvider.when('/Contactus', {
templateUrl: 'Templates/User/Contactus/Contactus.html',
controller: ''
});
$routeProvider.when('/Tutorregistration', {
templateUrl: 'Templates/User/Tutorregistration/Tutorregistration.html',
controller: ''
});
$routeProvider.when('/Tutorrequest', {
templateUrl: 'Templates/User/Tutorrequest/Tutorrequest.html',
controller: 'tutorequestController'
});
$routeProvider.otherwise({
redirectTo: '/Home',
templateUrl:'Templates/User/Home/Home.html'
});
});
Would appreciate your help with this.
The problem might be that MVC doesn't bind a checkbox value if it's false. Try this instead:
<div ng-controller="subjectController">
<div ng-repeat="sub in subjects" class="col-xs-12 col-sm-4">
<div class="chBoxPad">
<input ng-model="tutorRequest.tutorsubject" type="checkbox" id="{{sub.sub_id}}" name="{{sub.subject1}}" ng-true-value="{{sub.sub_id}}" />
<input type="hidden" value="false" name="{{sub.subject1}}" />
<label for="{{sub.sub_id}}"><span></span>{{sub.subject1}}</label>
</div>
</div>
</div>
If the checkbox is false, the hidden field will be submitted. Instead, when it's true, two fields will be submitted at the same time (false and true) and MVC will get that as a "true" value.
I know it sounds odd, but that it how MVC works. You can see that yourself if you use #Html.CheckBoxFor(). You'll have the same output.
The problems lie in the fact that you put the same ng-model for every subject. Angular don't build an array for a list of checkboxes, you have to bind every checkbox to a separate model.
The best way of doing that is to initialize you tutorsubject with all the values possible and a field 'checked' set to false like this :
angular.module("app", []).controller("ctrl", ['$scope', function($scope){
$scope.tutorRequest = {tutorsubject : [{sub_id:1, subject1:"Foo"},
{sub_id:2, subject1:"Foo2"}]};
angular.forEach($scope.subjects,function(subject){
var sub = angular.merge({checked:false}, subject);
$scope.tutorRequest.tutorsubject.push(sub);
});
$scope.allSubjectChecked = [];
$scope.updateChecked = function(){
console.log($scope.tutorRequest.tutorsubject);
$scope.allSubjectChecked = [];
angular.forEach($scope.tutorRequest.tutorsubject, function(sub){
if(sub.checked){
$scope.allSubjectChecked.push(sub);
}
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="sub in tutorRequest.tutorsubject" class="col-xs-12 col-sm-4">
<div class="chBoxPad" >
<input ng-model="tutorRequest.tutorsubject[$index].checked" type="checkbox" id="{{sub.sub_id}}" name="{{sub.subject1+'_'+$index}}" ng-change="updateChecked()"/>
<label for="{{sub.sub_id}}"><span></span>{{sub.subject1}}</label>
</div>
</div>
<h2> Subject selected : </h2>
<div ng-repeat="selected in allSubjectChecked">
<span ng-bind="selected.subject1"></span><br/>
</div>
</div>
Of course if this way of storing the data don't match to your backend; you can filter them when submitting the form. In order to not change the model displayed when doing that, perform this in the result of a var myData = angular.merge({},$scope.tutorRequest);
EDIT : change sample code by working snippet

how to get all options of select using angularjs

I need to get all options of a multiple select using angularjs, there are selected or not. The options are dynamic. No always the select have the same options.
HtML:
<div class="row">
<div class="form-group col-xs-5">
<label>Select 1</label>
<select multiple="multiple" class="form-control" id="origen" name="origen[]">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
</div>
<div class="form-group col-xs-2 buttoms-left-right">
<p>
<br />
<button type="button" class="btn btn-default" id="goright"><span class="glyphicon glyphicon-chevron-right"></span></button>
</p>
<p>
<button type="button" class="btn btn-default" id="goleft"><span class="glyphicon glyphicon-chevron-left"></span></button>
</p>
</div>
<div class="form-group col-xs-5">
<label>Select 2</label>
<select multiple="multiple" class="form-control" id="destino" name="destino[]" ng-model="formData.tags"></select>
</div>
</div>
I have e jquery that pass data from select 1 to select 2. I need all select 2 options, but using angularjs
jQuery(document).ready(function(){
jQuery('#goright').click(function() { return !jQuery('#origen option:selected').remove().appendTo('#destino'); });
jQuery('#goleft').click(function() { return !jQuery('#destino option:selected').remove().appendTo('#origen'); });
});
And in angularjs I have:
angular.module('formDS', ['ngAnimate', 'ui.router'])
// router configurations
.controller('formDSController', function($scope, $http) {
$scope.formData = {};
$scope.processForm = function() {
console.log($scope.formData.tags); //return undefined
};
// other code
});
You need to store the option values in your controllers $scope.
Plunker
<label>Select 1</label>
<select multiple="multiple" class="form-control" id="origen" name="origen[]">
<option ng-repeat="opt in select1">{{opt}}</option>
</select>
....
<label>Select 2</label>
<select multiple="multiple" class="form-control" id="destino" name="destino[]" ng-model="select2">
<option ng-repeat="opt in select1">{{opt}}</option>
</select>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.select1 = ['A', 'B', 'C'];
});
Absolutely no reason to use jQuery.
You can specify all options values inside controller. and use ng-options directive for displaying it in your select element.
You can get all available options in $scope.list in controller only.
See the below example.
var app = angular.module('app', []);
app.controller('crtl', function($scope) {
$scope.list = ['A', 'B', 'C'];
$scope.selectedValue = 'A';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="crtl">
<select ng-options="item as item for item in list" ng-model="selectedValue"></select>
</div>
</div>
ng-options docs

AngularJS refresh smart table after inserting new record in Bootstrap Modal Form

I use angular-bootstrap and and Angular Smart table.
I have a modal form which adds new records to database and shows the list in my smart table. Adding new records is working fine but how do I refresh my smart table after a new record is inserted into the database.
Controller
//ajax request to gather data and list in smart table
october.controllers['dashboard/feeds'] = function ($scope, $filter , $request, $modal, $log, $http) {
$scope.api = $request('onFeeds', {success: function(data, scope){
this.success(data).done(function() {
$scope.rowCollection = [];
$scope.rowCollection = angular.fromJson(data.result);
$scope.displayedCollection = [].concat($scope.rowCollection);
});
}
});
}
//Modal
var ModalInstanceCtrl = function ($scope, $modalInstance, $request, $filter) {
$scope.save = function (data) {
$request('onAddFeed',
{data:data,
success: function(data){
this.success(data);
$scope.refresh();
$modalInstance.close();
}
});
};
};
Template
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">neue Feed eintragen!</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<input type=hidden ng-init="formInfo.user_id = {% endverbatim %} {{ user.id }} ">
{%verbatim %}
<div class="form-group">
<label for="inputName3" class="col-sm-2 control-label">Feed Name</label>
<div class="col-sm-8">
<input class="form-control" id="inputName3" placeholder="Feed Name" ng-model="formInfo.name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Feed Type</label>
<div class="col-sm-8">
<select ng-model="formInfo.feed_type" class="form-control">
<option>Select Feed Source</option>
<option value="api">API</option>
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
<option value="upload">Upload</option>
</select>
</div>
</div>
<div class="form-group" ng-show="formInfo.feed_type =='api'">
<label for="selectAPI" class="col-sm-2 control-label">Select API</label>
<div class="col-sm-8">
<select ng-change="selectAction(item.id)" ng-model="formInfo.network_id" ng-options="item.id as item.name for item in networks" class="form-control"> </select>
</div>
</div>
<div class="form-group" ng-repeat="setup in setups">
<label for="setup" class="col-sm-2 control-label">{{setup}}</label>
<div class="col-sm-8">
<input ng-model="formInfo['api_credentials'][setup]" class="form-control" placeholder="Enter your {{setup}}">
</div>
</div>
<div class="form-group" ng-show="formInfo.feed_type =='xml' || formInfo.feed_type =='csv' ">
<label for="inputPassword3" class="col-sm-2 control-label">Source</label>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-link"></i></div>
<input ng-model="formInfo.source" type="text" class="form-control" id="sourceInput" placeholder="URL">
</div>
</div>
</div>
</div>
<span>{{formInfo}}</span>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-click="save(formInfo)">Save</button>
<button type="button" class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
{data:data,
success: function(data){
this.success(data);
$scope.refresh();
$modalInstance.close();
}
In the above code Instead of $scope.refresh() use $route.reload() to
Update the records before closing Modal Instance.
reload() Causes $route service to reload the current route even if $location hasn't changed
To refresh the smart-table you can add or remove items or just recreate the array.
$scope.tableData = [].concat($scope.tableData);
The thing that worked for me (and appears to be causing you the problem) is to set displayedCollection to an empty array. Smart Table will fill it with whatever paged, filtered, or sorted data you designate. Something like this:
<table st-table="displayedCollection" st-safe-src="rowCollection">
All of a sudden, rowCollection.push(data) automatically updated the Smart Table.

Multiple controllers in a meanjs form, submitting empty values

I am calling some values from the database and putting them in a select box in a form, however, whenever i click on submit, it submits an empty value, i am thinking its because i am using multiple controllers in the form, from what i have gathered, i have to do something with scope in the controllers, but i have been unable to do that
Attached is a copy of the create-view file, the highlited portions are the multiple controllers.
Please how do i make it work? Thank you very much
<section data-ng-controller="CandidatesController">
<div class="page-header">
<h1>New Candidate</h1>
</div>
<div class="col-md-12">
<form class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="vision">Vision</label>
<div class="controls">
<textarea data-ng-model="vision" id="vision" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label" for="dob">Date Of Birth</label>
<div class="controls">
<input type="date" data-ng-model="dob" id="dob" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="post">Post</label>
<div class="controls">
<select data-ng-model="post" id="post" class="form-control">
<option value="Presidential">PRESIDENTIAL</option>
<option value="Provincial">PROVINCIAL</option>
<option value="Municipal">MUNICIPAL</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label" for="province">Province</label>
<div class="controls">
<select data-ng-model="province" id="province" class="form-control">
<option value="Gauteng">Gauteng</option>
<option value="Free-State">Free-State</option>
<option value="Kwazulu-Natal">Kwazulu-Natal</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label" for="municipal">Municipal</label>
<div class="controls">
<input type="text" data-ng-model="municipal" id="municipal" class="form-control" placeholder="municipal" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="party">Party</label>
<div class="controls">
<section data-ng-controller="PartiesController" data-ng-init="find()">
<select data-ng-model="party" class="form-control" ng-options="party.name for party in parties track by party.name">
</select>
</section>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
The candidate controller code
'use strict';
//Candidates controller
angular.module('candidates').controller('CandidatesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Candidates',
function($scope, $stateParams, $location, Authentication, Candidates ) {
$scope.authentication = Authentication;
// Create new Candidate
$scope.create = function() {
// Create new Candidate object
var candidate = new Candidates ({
name: this.name,
vision: this.vision,
dob: this.dob,
post: this.post,
province: this.province,
municipal: this.municipal,
party: this.party
});
// Redirect after save
candidate.$save(function(response) {
$location.path('candidates/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Candidate
$scope.remove = function( candidate ) {
if ( candidate ) { candidate.$remove();
for (var i in $scope.candidates ) {
if ($scope.candidates [i] === candidate ) {
$scope.candidates.splice(i, 1);
}
}
} else {
$scope.candidate.$remove(function() {
$location.path('candidates');
});
}
};
// Update existing Candidate
$scope.update = function() {
var candidate = $scope.candidate ;
candidate.$update(function() {
$location.path('candidates/' + candidate._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Candidates
$scope.find = function() {
$scope.candidates = Candidates.query();
};
// Find existing Candidate
$scope.findOne = function() {
$scope.candidate = Candidates.get({
candidateId: $stateParams.candidateId
});
};
}
]);

Resources