I didn't find a case similar to mine, but I'm just learning AngularJS so I probably am missing it. Just slap me upside the head and point me in the right direction if this was already a question. Anyways...
I made an Add User form for the work study site that I am working on, and I used AngularJS to do so. When it finds the module, it works swimmingly. Unfortunately, it finds it maybe one out of 5 times. 3 out of 5 times, I get absolutely nothing in the console. 1 out of 5 times, though, I get an AngularJS error.
Failed to instantiate module addUser due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.4.1/$injector/nomod?p0=addUser
at Error (native)
at http://localhost/kushal/html/body/angular.min.js:6:416
at http://localhost/kushal/html/body/angular.min.js:23:433
at a (http://localhost/kushal/html/body/angular.min.js:22:483)
at Q.bootstrap (http://localhost/kushal/html/body/angular.min.js:23:218)
at http://localhost/kushal/html/body/angular.min.js:37:314
at n (http://localhost/kushal/html/body/angular.min.js:7:322)
at g (http://localhost/kushal/html/body/angular.min.js:37:92)
at db (http://localhost/kushal/html/body/angular.min.js:40:367)
at d (http://localhost/kushal/html/body/angular.min.js:19:219
I read that maybe I am using a property in my module that is not supported, but I don't know which that would be. My add_user.js file is as follows:
$(document).ready(function() {
(function() {
var AddApp = angular.module('addUser', ['ngSanitize']);
AddApp.controller('AddUserController', ['$http', '$scope', function($http, $scope){
$scope.SchoolSelBox = null;
$scope.schoolList = [];
$scope.CitySelBox = null;
$scope.cityList = [];
$scope.StateSelBox = null;
$scope.stateList = [];
$scope.TypeSelBox = null;
$scope.typeList = [];
$scope.master = {};
var original = $scope.user;
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_schools'}).
success(function(data) {
$scope.schoolList = data;
console.log(data);
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_cities'}).
success(function(data) {
$scope.cityList = data;
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_states'}).
success(function(data) {
$scope.stateList = data;
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$http.post("lib/scripts/adding_user.php", {switch_id: '1', func: 'retrieve_account_types'}).
success(function(data) {
$scope.typeList = data;
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
$scope.addUser = function(user) {
$scope.master = angular.copy(user);
console.log($scope.master);
$http.post("lib/scripts/adding_user.php", {
switch_id: '1',
func: 'authenticate_user',
username: $scope.master.username,
email: $scope.master.email,
first: $scope.master.FName,
last: $scope.master.LName,
school: $scope.master.SchoolSelBox['school_id'],
city: $scope.master.CitySelBox['city_id'],
state: $scope.master.StateSelBox['state_id'],
account_type: $scope.master.TypeSelBox['security_level_id']
}).
success(function(response){
console.log(response);
if (response.length > 1) {
alert('An has error occured. Please contact an administrator at stem.admin#minotstateu.edu.'); //An error not caught below
} else {
var responseArray = response.split('');
for (var x = 0; x < responseArray.length; x++) {
switch (responseArray[x]) {
case "1":
$("#username_error").text("Username Already Taken");
break;
case "2":
$("#email_error").text("*");
$("#input_error").css("color", "#FF0000");
$("#input_error").text("An account is already registered for this email");
break;
case "3":
$("#input_error").css("color", "#6d962f");
$("#input_error").text("Account Successfully Added");
$scope.user = angular.copy(original);
$scope.addUserForm.$setPristine();
break;
case "4":
$("#input_error").css("color", "#FF0000");
$("#input_error").text("Account could not be added"); //PHP error
break;
default:
alert("add_user.js, add_user()"); //Not real sure what this does
break;
}
}
}
}).
error(function(data, status, headers, config) {
console.log(data, status, headers, config);
});
};
$scope.resetFrm = function() {
$scope.user = angular.copy(original);
$scope.addUserForm.$setPristine();
$("#username_error").text("");
$("#email_error").text("");
$("#input_error").text("");
};
}]);
})();
});
I don't know if you will need the HTML for this or not, so here is add_user.php:
<?php
session_start();
if (($_SESSION['sec_level']) != 4) {
header("Location: permission_error.php");
}
include "lib/header/header.php";
include "lib/linklib.php";
?>
<!DOCTYPE html>
<html ng-app="addUser">
<head>
<title>Add User</title>
<?php
csslib();
jslib();
?>
<script type="text/javascript" src="lib/js/add_user.js"></script>
</head>
<body >
<center><div id="bordercontainer">
<?php
headermenu();
?>
<div id="maincontainer">
<br />
<span class="header headerTextAlignment">Add User</span>
<br />
<center>
<br />
<div id="addusercontainer">
<form name="addUserForm" novalidate ng-controller="AddUserController as addUserCtrl" ng-submit="addUserForm.$valid && addUser(user)">
<!--Checks to see if the form is valid before submission using the $valid form controller. AND statement. ng = Angular JS -->
<div class="row-fluid">
<span class="adduser_heading">Username:</span>
<input type="text" id="username" class="adduser_input" size="35" ng-model="user.username" required ng-pattern="string"/>
<span class="adduser_error" id="username_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">Email:</span>
<input type="email" name="email" id="email" class="adduser_input" size="35" ng-model="user.email" required ng-pattern="string"/>
<span class="adduser_error" id="email_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">Confirm Email:</span>
<input type="email" name="email" id="confirm_email" class="adduser_input" size="35" ng-model="user.ConfEmail" required ng-pattern="string"/>
<span class="adduser_error" id="match_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">First Name:</span>
<input type="text" id="first" class="adduser_input" size="35" ng-model="user.FName" required ng-pattern="string"/>
<span class="adduser_error" id="first_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">Last name:</span>
<input type="text" id="last" class="adduser_input" size="35" ng-model="user.LName" required ng-pattern="string"/>
<span class="adduser_error" id="last_error"></span>
</div>
<div class="row-fluid">
<span class="adduser_heading">School:</span>
<select ng-model="user.SchoolSelBox" ng-options="name.school_name for (key, name) in schoolList" id="school" class="adduser_input" style="width: 264px;" required></select>
</div>
<div class="row-fluid">
<span class="adduser_heading">City:</span>
<select ng-model="user.CitySelBox" id="city" class="adduser_input" style="width: 264px;" ng-options="name.city_name for (key, name) in cityList" required></select>
</div>
<div class="row-fluid">
<span class="adduser_heading">States:</span>
<select ng-model="user.StateSelBox" id="state" class="adduser_input" style="width: 264px;" ng-options="name.state_name for (key, name) in stateList" required></select>
</div>
<div class="row-fluid">
<span class="adduser_heading">Account Type:</span>
<select ng-model="user.TypeSelBox" id="account_type" class="adduser_input" style="width: 264px;" ng-options="name.security_level_type for (key, name) in typeList" required></select>
</div>
<div class="row-fluid">
<div class="adduser_button_left">
<button class="btn btn-primary" type="reset" id="reset" value="Reset" >Reset</button>
</div>
<span class="adduser_large_error" id="input_error"></span>
<div class="adduser_button_right">
<button type="submit" class="btn btn-primary" id="submit" value="Submit" >Submit</button>
</div>
</div>
</form>
</div>
<br />
</center>
<!-- Load Modal -->
<div id="loadModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-body">
<div class="progress">
<div class="bar" style="width: 0%; " data-percentage="100" ></div>
</div>
<span id="comment"></span>
</div>
</div>
</div>
</div>
</body>
</html>
I do have Angular JS and ngSanitize included in that lib/linklib.php file. All those console.log()'s are there for feedback. The JS goes to PHP back-end code which interacts with the database. If you need any more information, I will try and get it up asap. Just a bit stumped since it seems to be happening 1/5 times.
Oh, this is through localhost. I have my own copy of the code and the database, so I am not going through a firewall or gateway or anything like that to access the database. Don't know if that matters, just tossing it out there.
Thanks.
Edit: Should probably mention what happens when it does not work. The HTML loads just fine, but the select boxes do not populate. Clicking the Submit and Reset button don't do anything.
I removed the jQuery $(document).ready, as per o4ohel's suggesstion, and it works swimmingly and consistently now. Thanks!
Related
I am trying to save a ViewModel object from a partial view in a modal, and I get a 404 error when I try to post it. The url is being called, but the ViewModel data isn't being sent. I have been reading similar questions on here and on MSN for hours and nothing I've tried fixes the problem. I took out the repetitive days of the week code for brevity, but I can
add them back in if anyone wants a complete working example. Here is the code
EmployeeViewModel
public class EmployeeViewModel
{
public bool Monday { get; set; } = false;
//...bool properties for Tuesday through Sunday
public Employee Employee { get; set; }
}
Employee/ _AddEmployeeModalPartial
#model JSarad_C868_Capstone.ViewModels.EmployeeViewModel
#Html.AntiForgeryToken()
<div class="modal modal-fade" id="addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addEmpoyeeLabel">Add Employee</h4>
<button type=button class="close" data-bs-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Add">
<div class="form-group">
<input asp-for="Employee.Id" class="form-control" />
<input asp-for="Employee.Availability" class="form-control" />
<label asp-for="Employee.Role"></label>
<select asp-for="Employee.Role" class="form-control">
<option value="Bartender">Bartender</option>
<option value="Server">Server</option>
</select>
<span asp-validation-for="Employee.Role" class="text-danger"></span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Name"></label>
<input asp-for="Employee.Name" class="form-control" />
<span asp-validation-for="Employee.Name" class="text-danger"></span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Phone"></label>
<input asp-for="Employee.Phone" class="form-control" />
<span asp-validation-for="Employee.Phone" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Email"></label>
<input asp-for="Employee.Email" class="form-control" />
<span asp-validation-for="Employee.Email" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Address"></label>
<input asp-for="Employee.Address" class="form-control" />
<span asp-validation-for="Employee.Address" class="text-danger">
</span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label>Availabiliy</label>
</div>
<div class="row pb-4">
<div class="col">
<div class="form-check">
<input asp-for="Monday" class="form-check-input"
type="checkbox" />
<label asp-for="Monday" class="form-check-label"></label>
</div>
<!--...//form check boxes for Tuesday trough Sunday -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-bs-save="modal">Save</button>
</div>
</div>
</div>
</div>
EmployeeController.cs
[HttpGet]
public IActionResult Add()
{
EmployeeViewModel viewModel = new EmployeeViewModel();
return PartialView("_AddEmployeeModalPartial", viewModel); ;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(EmployeeViewModel viewModel) //code never reaches this Action
{
viewModel.Employee.Availability = ConvertDaysToChar(viewModel.Employee.Availability)
if (ModelState.IsValid)
{
_db.Employees.Add(viewModel.Employee);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return PartialView("_AddEmployeeModelPartial", viewModel);
}
}
site.js
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
/* event.preventDefault();*/
var url = $(this).data('url');
console.log(url)
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var sendViewModel = form.serialize();
console.log(sendViewModel);
//$.post(actionUrl, sendViewModel).done(function (data) {
// PlaceHolderElement.find('.modal').modal('hide');
/*above is the code from a tutorial for modals. It also doesn't send the object to
post action*/
$.ajax({
type: 'POST',
url: actionUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendViewModel),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
})
})
When I click the save button on the model, the console.log(sendViewModel) returns the correct Serialization with all of the properties and their correct names. And the properties change correctly when there is input.
Employee.Id=&Employee.Availability=&Employee.Role=Bartender&Employee.Name=&Employee.Phone=&Employee.Email=&Employee.Address=&Monday=false&Tuesday=false&Wednesday=false&Thursday=false&Friday=false&Saturday=false&Sunday=false
But I get an error "Failed to load resource: the server responded with a status of 404 ()"
and when I check it the page says "No webpage was found for the web address: https://localhost:44313/Add HTTP ERROR 404" as if it's trying to get a post. It is also missing the controller, but if I change my form action to "Employee/Add" in the _Partial view it still doesn't send the data along with the url, which is causing an entirely different problem. I would greatly appreciate any help or guess or input of any kind. I'm about five seconds away from throwing my laptop out the window on this one. Thanks.
1.Remove the #Html.AntiForgeryToken() inside your form,like below:
<form action="Add" >
#Html.AntiForgeryToken()
....
Then after you serialize the form you can get the AntiForgeryToken, like below:
Because when you don't add #Html.AntiForgeryToken()inside form, after you serialize the form you don't get the AntiForgeryToken, like below:
Besides, if you use <form asp-action="Add" > In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add #Html.AntiForgeryToken(),you can find in the below :
2.change your ajax like below:
$.ajax({
type: 'POST',
url:'/Employee/Add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: sendViewModel,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
result:
First, I had to change the form action from "Add" to "Employee/Add". ThenI had to remove the antiforgery token from my post action. The first code that is commented out actually works fine otherwise. In my defense I did remove the antiforgery token when I had the wrong URL, but I forgot to retest that when I had the correct one.
I'm using angularjs to create a modal used by a form.
In my javascript I receive only two fields of my form (name and clientVersion) the other two are omitted and I don't know why.
This is my modal:
<div class="modal" id="addUserModal" data-ng-app="myApp">
<div class="modal-dialog" data-ng-controller="modalController">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">New user</h4>
</div>
<div class="modal-body">
<form novalidate class="simple-form">
<!-- form start -->
<div class="box-body">
<div class="form-group">
<label>Name</label> <input id="name" type="text"
data-ng-model="newUser.name" class="form-control"
maxlength="30" placeholder="Version name" required>
</div>
<div class="form-group">
<label>Role</label> <select class="form-control select2"
style="width: 100%;" name="role" data-ng-model="newUser.role"
data-ng-options="user.idRole as role.role for role in roles track by role.role">
</select>
</div>
<div class="form-group">
<label>Client Version </label> (optional) <select
class="form-control select2" style="width: 100%;"
name="version" data-ng-model="newUser.clientVersion"
data-ng-options="version.idClientVersion as version.name for version in versions track by version.name">
</select>
</div>
<div class="form-group">
<label>Enable </label> <input type="checkbox"
data-ng-model="newUser.enabled" name="my-checkbox" checked>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button id="uploadVersionButton" type="button"
class="btn btn-primary" data-ng-click="createUser(newUser)">Create
user</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
In my javascript code I have
//Angular section for Select2 of modal create user
var app = angular.module('myApp',[]);
app.controller('modalController', function($scope, $http) {
$http({
method: 'GET',
url: 'roles'
}).then(function successCallback(response) {
$scope.roles = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$http({
method: 'GET',
url: 'version',
}).then(function successCallback(response) {
$scope.versions = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.createUser = function(newUser) {
$scope.master = angular.copy(newUser);
};
});
and newUser has only those two fields. Do you know why?
First error is in
data-ng-options="role.idRole as role.role for role in roles track by role.role"
I gave the wrong idRole.
The checkbox is a prolem of bootstrap plugin, without it all works.
I found this directive and work:
app.directive('bootstrapSwitch', [
function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
element.bootstrapSwitch();
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if (newValue) {
element.bootstrapSwitch('state', true, true);
} else {
element.bootstrapSwitch('state', false, true);
}
});
}
};
}
]);
but perhaps it is better to use
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state)
and store state into a variable.
I have my database with Firebase and now I'm trying to do a newsletter subscription, but I want to save the subscribers in Mailchimp and Firebase.
Mailchimp connection works perfectly, but I don't know how to integrate the Firebase connection in the same js.
This is what I have in the <head> tag
<script type="text/javascript">
angular.module("productLaunch", ["mailchimp"])
</script>
This in the <body> tag
<body ng-app="productLaunch"><section class="container-fluid subscribe" ng-controller="MailchimpSubscriptionCtrl">
<div class="wrapper">
<!-- Let us your email -->
<div class="">
<h2 class="text-center">Subscribe to our news</h2>
<div class="col-lg-4 col-lg-offset-4 mt centered">
<h4 ng-hide="mailchimp.result ==='success'">LET ME KNOW WHEN YOU LAUNCH</h4>
<h4 ng-show="mailchimp.result ==='success'">THANKS FOR SIGNING UP!</h4>
</div>
<form class="form-inline" role="form" ng-hide="mailchimp.result === 'success'">
<input class="hidden" type="hidden" ng-model="mailchimp.username" ng-init="mailchimp.username='stopappweb'">
<input class="hidden" type="hidden" ng-model="mailchimp.dc" ng-init="mailchimp.dc='us12'">
<input class="hidden" type="hidden" ng-model="mailchimp.u" ng-init="mailchimp.u='3eb39be3ad857e60b357fdb5e'">
<input class="hidden" type="hidden" ng-model="mailchimp.id" ng-init="mailchimp.id='520ddfd981'">
<div class="form-group">
<label class="sr-only" for="mailchimp.email">Email address</label>
<input type="email" class="form-control" id="mailchimp.email" placeholder="Enter email" ng-model="mailchimp.email">
</div>
<button type="submit" class="btn btn-info" ng-disabled="MailchimpSubscriptionForm.$invalid" ng-click="addSubscription(mailchimp)" type="submit" value="SIGN UP" disabled="disabled">Submit</button>
<div ng-show="mailchimp.result === 'error'">
<p ng-bind-html="mailchimp.errorMessage" class="error"></p>
</div>
</form>
</div>
</div>
</section>
And this is my JS:
'use strict';
angular.module('mailchimp', ['ng', 'ngResource', 'ngSanitize'])
.controller('MailchimpSubscriptionCtrl', ['$log', '$resource', '$scope',
function ($log, $resource, $scope) {
$scope.myData = new Firebase("https://stopappwebpre.firebaseio.com/subscriptors");
// Handle clicks on the form submission.
$scope.addSubscription = function (mailchimp) {
var actions,
MailChimpSubscription,
params,
url;
$scope.myData.push({mailchimp.email:$scope.mailchimp.email});
// Create a resource for interacting with the MailChimp API
url = 'http://' + mailchimp.username + '.' + mailchimp.dc + '.list-manage.com/subscribe/post-json';
params = {
'EMAIL': mailchimp.email,
'FNAME': mailchimp.fname,
'LNAME': mailchimp.lname,
'c': 'JSON_CALLBACK',
'u': mailchimp.u,
'id': mailchimp.id
};
actions = {
'save': {
method: 'jsonp'
}
};
MailChimpSubscription = $resource(url, params, actions);
// Send subscriber data to MailChimp
MailChimpSubscription.save(
// Successfully sent data to MailChimp.
function (response) {
// Define message containers.
mailchimp.errorMessage = '';
mailchimp.successMessage = '';
// Store the result from MailChimp
mailchimp.result = response.result;
// Mailchimp returned an error.
if (response.result === 'error') {
if (response.msg) {
// Remove error numbers, if any.
var errorMessageParts = response.msg.split(' - ');
if (errorMessageParts.length > 1)
errorMessageParts.shift(); // Remove the error number
mailchimp.errorMessage = errorMessageParts.join(' ');
} else {
mailchimp.errorMessage = 'Sorry! An unknown error occured.';
}
}
// MailChimp returns a success.
else if (response.result === 'success') {
mailchimp.successMessage = response.msg;
}
},
// Error sending data to MailChimp
function (error) {
$log.error('MailChimp Error: %o', error);
}
);
}; }]);
Thank you so much for your help.
I have an HTML form that is inserting successfully data into a database, but is not showing the data in the table below it. The only way to check we have to use is to manually refresh the page. The same happen with delete, sometimes a dialog is shown, telling us that value was deleted, but we still have two referesh the page to see the change.
Is there any fucntion to reload that listing?
Any help would be appreciated
Here is my angular html Named as : manage_features.html
<!-- START panel-->
<div class="panel panel-default">
<div class="panel-heading">
<h3>Manage Features Name</h3>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" ng-model="rec.Name" placeholder="Name" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox c-checkbox">
<label>
<input type="checkbox" ng-model="rec.isSpecial">
<span class="fa fa-check"></span>is Special</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox c-checkbox">
<label>
<input type="checkbox" ng-model="rec.isMultiple">
<span class="fa fa-check"></span>Is Multiple</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="button" ng-click="add(rec)" class="btn btn-sm btn-default">ADD</button>
</div>
</div>
</form>
</div>
</div>
<!-- END panel-->
here is my JS file named as manage_features.js
$scope.add = function(rec){
console.log(rec);
$scope.upload = $upload.upload({
url: 'api/AdminArea/feature/add', //upload.php script, node.js route, or servlet url
method: 'POST',
headers: {'header-key': '83c238df1650bccb2d1aa4495723c63f07672ee8'},
withCredentials: true,
data:{data:rec},
}).success(function(data, status, headers, config) {
console.log(data);
return false;
toaster.pop('success', 'Add', 'Record added successfully.');
$scope.$root.$broadcast("myDocEventReload", {});
});
};
here is delete function
$scope.delete = function (id) {
console.log(id);//return false;
ngDialog.openConfirm({
template: 'modalDeleteDialogId',
className: 'ngdialog-theme-default'
}).then(function (value) {
$http
.post('api/AdminArea/feature/delete', {id:id})
.then(function (res) {
console.log(res.data);
if(res.data != 1){
toaster.pop('success', 'Deleted', 'Record deleted successfully.');
}
else{
toaster.pop('error', 'Deleted', 'Record can\'t be deleted!');
}
});
}, function (reason) {
console.log('Modal promise rejected. Reason: ', reason);
});
//if(popupService.showPopup('Would you like to delete?')) {
// }
};
The main point, that I can basically see in your code, is that the object 'rec' is used 'freely' and for this reason when you receive the response from the server you are not populating the correct object.
The reason for this is that when you are calling .then(function (res) { the 'res' variable is confined in the scope of that particular function, and won't change the value of the scope variable.
my advice is to do something like this:
create a controller
angular.module('mymodule',[]).controller('myCtrl',['$upload','toaster' function($upload, toaster){
var self = this;
self.rec = {};
self.add = function(){
$upload.upload({
url: 'api/AdminArea/feature/add', //upload.php script, node.js route, or servlet url
method: 'POST',
headers: {'header-key': '83c238df1650bccb2d1aa4495723c63f07672ee8'},
withCredentials: true,
data:{data:self.rec},
}).success(function(data, status, headers, config) {
/* THIS RETURN WAS BLOCKING THE NEXT, YOU HAVE TO REMOVE IT
console.log(data);
return false;*/
toaster.pop('success', 'Add', 'Record added successfully.');
/*$scope.$root.$broadcast("myDocEventReload", {});*/
});
}
self.delete = function(id){
console.log(id);//return false;
ngDialog.openConfirm({
template: 'modalDeleteDialogId',
className: 'ngdialog-theme-default'
}).then(function (value) {
$http
.post('api/AdminArea/feature/delete', {id:id})
.then(function (response) {
console.log(response.data);
if(response.data != 1){
toaster.pop('success', 'Deleted', 'Record deleted successfully.');
}
else{
toaster.pop('error', 'Deleted', 'Record can\'t be deleted!');
}
});
}, function (reason) {
console.log('Modal promise rejected. Reason: ', reason);
});
};
}
Then you can use this controller in your code with
<div ng-controller='myCtrl as c'>
<input type="checkbox" ng-model="c.rec.isMultiple">
</div>
When you change the object rec inside the controller the changes will be visible automatically in the html.
It's a simple answer to tell you the idea of what I think you should do with angular.
I'm trying to code a controller so some inputs get disabled after changes in another one.
This is the controllre:
app.controller('SignUpController',function ($scope, $http) {
this.unavaliable = true
this.userUnavaliable = function() {
console.log(this.unavaliable)
return this.unavaliable
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
this.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
this.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
As my markup below shows, one input should obtain a certain class, and another one should get disabled when unavaliable is set to true. But even I can get to the console.log(), the variable seems to never get true.
This is my markup:
<form class="form-inline" role="form">
<div class="form-group">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)" ng-class="{'has-error':signup.userUnavaliable()}">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Contraseña" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable" >Registrar</button>
</form>
I tried with $scope instead of this but never got it to work that way
Try this:
app.controller('SignUpController',function ($scope, $http) {
var that = this;
that.unavaliable = true;
that.userUnavaliable = function() {
console.log(that.unavaliable)
return that.unavaliable
}
that.userExists = function(mail) {...
Your issue seems to be related to JS Context; in the example above it is preserved in that variable. That is how it is done in JOhn's Papa approach