$scope unidefined in modal angular js - javascript

i am using modal in angular but when modal open so here values are not binding with model i don't know why this happening must be appreciates if some corrected if there is any mistake thanx.
modal.html
<script type="text/ng-template" id="categoryModal.html">
<form class="form-horizontal" name="category_form" novalidate>
<div class="modal-header">
<a class="close" ng-click='cancel()'><i class="icon-remove-circle icon-bold"></i> </a>
<h3>Category</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="category_Name" class="col-lg-3 form-label">Category Name:</label>
<div class="col-lg-8">
<input class="form-control" id="category_Name" ng-model="category.name" name="category_Name" placeholder="Category Name" required/>
<div class="error" ng-show="category_form.category_Name.$dirty && category_form.category_Name.$invalid">
<small class="error errorFields" ng-show="category_form.category_Name.$error.required">
Category Name is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button ng-click='saveCategory()' class="btn btn-primary" ng-disabled="category_form.$invalid">
<i class="icon-ok-sign icon-white"></i> Add
</button>
<button ng-click='cancel()' class="btn btn-warning">
<i class="icon-remove-circle icon-white"></i> Cancel
</button>
</div>
</form>
</script>
modalController.js
app.controller('brandModalCtrl', function ($rootScope, $scope, $modalInstance) {
// Save Brand
$scope.saveCategory = function () {
console.log($scope.category) // undefined
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});

I would try adding the same $scope to modalOptions and letting the modal share the controller's $scope variables. Putting both onto $rootScope is too drastic. Ideally, your modal should have an isolate scope, but it sounds like you need some overlap.

Related

Writing to new local file from javascript MVC

I have a dropdown meny in a shared layout that have one option that is called "mail me".
Once the "mail me" is pressed, a pop-up modal comes up which can be filled with mail, number and message.
PROBLEM/CHALLENGE: Nothing (viewModel) seems to get passed from my the javascript on the shared layout .cshtml to the back-end. I would like to first of have my values passed to the controller correctly so I can write the info to a file which I then can review and contact whoever filled in the box.
Modal code `
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Kontakt</h4>
</div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="telefonnummer"><span class="glyphicon glyphicon-earphone"></span> Telefonnummer</label>
<input type="number" class="form-control" id="telefonnummer" placeholder="Ange telefonnummer">
</div>
<div class="form-group">
<label for="email"><span class="glyphicon glyphicon-envelope"></span> Email</label>
<input type="text" class="form-control" id="email" placeholder="Ange email">
</div>
<div class="form-group">
<label for="meddelande"><span class="glyphicon glyphicon-pencil"></span> Meddelande</label>
<input type="text" class="form-control" style="height:50px" id="meddelande" placeholder="Ange meddelande">
</div>
<button type="submit" class="btn btn-block" onclick="SkickaMail()">
Skicka
<span class="glyphicon glyphicon-ok"></span>
</button>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal">
<span class="glyphicon glyphicon-remove"></span> Avbryt
</button>
#*<p>Need help?</p>*#
</div>
</div>
</div>
</div>`
"SkickaMail" is supposed to call the Javascript and send a viewModel.
It's suppose to send the val:s to the controller page PeopleController and the IactionResult Kontakt but nothing gets passed to the controller, the vals are null when I debug in the controller.
Code below
<script>
//DEN HÄR DELEN FUNKAR INTE, VÄRDENA SKICKAS INTE KORREKT TILL CONTROLLERN AV NÅGON ANLEDNING.
function SkickaMail() {
var dataX = {
//.val()metoden nedan är jQuery
"#nameof(MVCrepetition.Models.ViewModels.Mail.TelNummer)": $("##nameof(Model.TelNummer)").val(),
"#nameof(MVCrepetition.Models.ViewModels.Mail.EMail)": $("##nameof(Model.EMail)").val(),
"#nameof(MVCrepetition.Models.ViewModels.Mail.Meddelande)": $("##nameof(Model.Meddelande)").val()
}
$.post("/Kontakt", dataX, function (json) {
})
}
</script>
Controller code:
[HttpPost]
public IActionResult Kontakt(Mail viewModel)
{
Mail mail = new Mail();
mail.TelNummer = viewModel.TelNummer;
mail.EMail = viewModel.EMail;
mail.Meddelande = viewModel.Meddelande;
System.IO.File.WriteAllText(#"c:\Users\Administrator\Desktop\LiveTradingProject\mailfromcontact.json", JsonConvert.SerializeObject(mail));
//using (StreamWriter file = File.CreateText(#"c:\movie.json"))
// {
// JsonSerializer serializer = new JsonSerializer();
// serializer.Serialize(file, movie);
// }
return null;
}
I hit the breakpoint on server side but the viewModels values are all null
enter image description here
I hadn't used ID properly in my Modal, that was the issue. The Id's now match the val:s and it works.

How to get input from user display in HTML page

I encounter a problem to display input from user into this table.
<tr ng-repeat="user in users" ng-class-even="'bg-light-grey'" ng-if="isLoading==false">
<td>
<div> {{user.username}} </div>
</td>
<td>
<div> {{user.name}} </div>
</td>
</tr>
If user click this "edit user" button, the form will appear.
<div class="glyphicon glyphicon-lock" ng-click="editUser();">
This is form that require user to fill edit their username and name
<div class="dialog-contents">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Edit User</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<form name="edituser">
<div class="form-group has-feedback" ng-class="editUser.username.$valid ? 'has-success' : 'has-error';">
<label class="col-sm-2 control-label" for="Username">Username</label>
<div class="col-sm-10">
<input type="username" ng-model="user.username" class="form-control" id="Username" placeholder="Enter Username"/>
</div>
<span class="glyphicon form-control-feedback"
ng-class="addUser.username.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>
<div class="form-group has-feedback" ng-class="editUser.name.$valid ? 'has-success' : 'has-error';">
<label class="col-sm-2 control-label" for="Name">Name</label>
<div class="col-sm-10">
<input type="name" ng-model="user.name" class="form-control" id="name" placeholder="Enter Name"/>
</div>
<span class="glyphicon form-control-feedback"
ng-class="addUser.name.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>
Form this form, if user click this "submit" button, the user details will appear in table as i provide the code above.
<button type="submit" class="btn btn-primary" ng-click="add();"
ng-class="isLoading ? 'disabled' : '';">Submit </button>
Now, i want to push the input from user, and display it in the table. But i am stuck in developing the controller to get the input and displayed it. Appreciate if someone can help solve this problem.
app.register('user', ['$scope', 'ngDialog', function ($scope, $dialog) {
$scope.isLoading = false;
$scope.addUser = function(){
$dialog.open({
showClose: false,
closeByEscape: true,
template: 'view/user/user-user-add.html',
controller: ['$scope', function ($dialogScope) {
$dialogScope.users = {
username : "" ,
name : "",
status : "",
}
.closePromise.then(function (data)
$dialogScope.hasError = false;
$dialogScope.errorMessage = '';
$dialogScope.add=function(){
$dialogScope.closeThisDialog({username:"xxx"});
}
}]
});
};
}]);
In your add function, close the dialog and pass the new user object to close promise, like this: -
//your dialog controller
$dialogScope.add=function(){
$dialogScope.closeThisDialog({username:"xxx"});
};
you main controller: -
$scope.addUser = function(){
$dialog.open({
....
})
.closePromise.then(function (data) {
console.log(data);
//check and find user from the data and do what you need, i.e. $scope.users.push(user);
});
};

Angular form inputs to array with Validation

Is there a way in angular js to push a list of managers(or any item) to an array with validation in angular. I basically want to create an array as the ng-model and still validate it. Is this possible to do or am i going about it the wrong way?
var app = angular.module("FormTest",[]);
app.controller("AppCtrl", ["$scope", function($scope){
var appCtrl = this;
appCtrl.appName = "Form Array";
$scope.managers = [""];
$scope.form = {};
$scope.form.managers = $scope.managers;
$scope.addManager = function(){
$scope.managers.push('');
}
$scope.removeManager = function(index){
if($scope.managers.length > 1){
$scope.managers.splice(index, 1);
}
}
}])
angular.element(document).ready(function(){
angular.bootstrap(document.querySelector('html'), ["FormTest"]);
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div ng-controller="AppCtrl as app">
<h2>{{app.appName}}</h2>
<div>
{{form.managers}}
<div>
<div>{{managers}}</div>
<div class="btn btn-primary" ng-click="addManager()">add manager</div>
</div>
</div>
<form novalidate name="form">
<div class="form-group" ng-repeat="item in managers track by $index">
<div class="row-fluid">
<div class="col-md-5">
<input type="text" ng-model="managers[$index]" ng-pattern="/\w{3,}/" required class="form-control">
</div>
<div class="col-md-1">
<div class="btn btn-default">
<span class="glyphicon glyphicon-remove-circle" ng-click="removeManager($index)"></span>
</div>
</div>
</div>
</div>
</form>
</div>
In your example, all right, except for that of the regular expression.
Look at the example code jsfiddle.
<h2>{{app.appName}}</h2>
<div>
{{form.managers}}
<div>
<div>{{managers}}</div>
<button class="btn btn-primary" ng-click="addManager()">add manager</button>
</div>
</div>
<form novalidate name="form">
Form valid={{form.$valid|json}}
<div class="form-group" ng-repeat="item in managers track by $index">
<div class="row-fluid">
<div class="col-md-5">
<input type="text" ng-model="managers[$index]" name="manager{{$index}}" ng-pattern="/^\w{3,}$/" required class="form-control">
{{form['manager'+$index].$error}}
</div>
<div class="col-md-1">
<div class="btn btn-default">
<button class="glyphicon glyphicon-remove-circle" ng-click="removeManager($index)">Remove</button>
</div>
</div>
</div>
</div>
</form>

ng-submit not working in angularjs

My view:
<div class="modal" tabindex="-1" role="dialog" ng-controller="LocationController">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="$hide()">×</button>
<h4 class="modal-title">
Add a Location
</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" ng-submit="createLocation()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Warehouse A, Row 15, Shelf BC1, etc" ng-model="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="warehouse, row, shelf, etc" ng-model="type">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" ng-click="$hide()">Cancel</button>
</div>
</div>
</div>
</div>
My controller:
angular.module('mean').controller('LocationController', ['$scope', '$location', '$rootScope', 'LocationService', '$modal', '$routeParams', function ($scope, $location, $rootScope, LocationService, $modal, $routeParams) {
$scope.createLocation = function() {
alert('afds');
LocationService.create(this).then(function(response) {
console.log(response);
});
}
}]);
Yet, when I click save, I don't get the alert. Not sure what's going on there.
Thanks to Matt Way's comment - turns out my save button was outside my form. Fixed
Even if the button is inside the form and still ng-submit is not working then change your button type to submit.
<button type="submit" class="btn btn-success" ng-click="login()">Login</button>
P.S: Other answers did not help me until I changed the button type to submit. Hope this helps.
Maybe you should add 'novalidate' attribute on the form tag to avoid native browser validation as indicated here https://docs.angularjs.org/guide/forms
This affects too, there has to be a submit button in the form (button or input type="submit") or ng-submit won't work.
for me the problem was 'required' tag on one of the form fields. After removing this tag the form worked again. The old way of solving such problems is to try to comment part of your form and to run the code.
I prefer using 'novalidate' tag on the form, and button with type="submit" , so that the validation of the form is done by angular.
Silliest mistake ever, make sure you are compiling your js code.

How to load form with values based on Angular $resource

I want CRUD operations so that when a user clicks on any particular item to edit this form will be filled with those values (that the user wants to edit).
Here is my code .
storeView.html
<tr data-ng-repeat="store in stores | filter:search | orderBy:'name'">
<td>
{{ store.name }}
</td>
<td class="icons-width">
<a href="#/Store/edit/{{store._id}}" id="edit" data-toggle="tooltip">
<i class="fa fa-pencil fa-fw colorInfo" ></i>
</a>
<a ng-click="deleteStore(store._id)" id="delete" data-toggle="tooltip">
<i class="icon-trash"></i>
</a>
</td>
</tr>
So when a user clicks on edit for a particular store it will go to another view which has the a form that will show which values the user wants to edit.
storeformView.html
form class="form-horizontal" name="store_form" novalidate ng-submit='AddStore()'>
<div class="modal-header">
<h3>Create/Edit Store</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label for="store_Name" class="col-lg-4 form-label">Name:</label>
<div class="col-lg-7">
<input type="text" class="form-control" ng-model="store.name" id="store_Name" name="store_Name" placeholder="Store Name" required/>
<div class="error" ng-show="store_form.store_Name.$dirty && store_form.store_Name.$invalid">
<small class="error errorFields" ng-show="store_form.store_Name.$error.required">
Store Name is required.
</small>
</div>
</div>
</div>
<div class="form-group">
<label for="store_AddressLine1" class="col-lg-4 form-label">Address Line 1:</label>
<div class="col-lg-7">
<input type="text" class="form-control" ng-model="store.address1" id="store_AddressLine1" name="store_AddressLine1" placeholder="Address Line 1" required/>
<div class="error" ng-show="store_form.store_AddressLine1.$dirty && store_form.store_AddressLine1.$invalid">
<small class="error errorFields" ng-show="store_form.store_AddressLine1.$error.required">
Address is required.
</small>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-disabled="store_form.$invalid">
<i class="icon-ok-sign icon-white"></i> Save
</button>
<a class="btn btn-default" href="#/Stores">
<i class="icon-remove-circle" ></i>
Cancel
</a>
</div>
</form>
storeFactory.js
app.factory('Store', function ($resource) {
return {
getAllStores : $resource("/store/list" ,{},{ TypeGetStores:{method: 'get', isArray:true}}),
getStore : $resource("/store/:id" ,{id : #id},{ TypeGetStore:{method: 'get'}}),
};
});
app.js
var app = angular.module('myApp', ['ngCookies','ngResource', 'ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/Stores',
{
templateUrl: '/app/partials/StoresListView.html'
})
.when('/Store/edit/:storeId',
{
templateUrl: '/app/partials/StoreFormView.html'
})
.otherwise({ redirectTo: '/Login' });
});
For loading information about your store, you can use resolve parameter in routeProvider :
.when('/Store/edit/:storeId',
{
templateUrl: '/app/partials/StoresListView.html',
resolve: {app: function($scope,Store,$routeParams) {
$scope.store = Store.getStore({id:$routeParams.id})
}
}
If everything is right and that's how your factory will work (if that function really returns store. Maybe it returns JSON with root, then you should specify, how to get store from that JSON), than you will have $scope.store in your controller, and it will be two-way-binded with what you have in form.
Note: page will load only after resolve is fully done.

Categories