unable to get data from html in angular js - angularjs

in this code of HTML, we get input text value and send to the Angular controller
so they get to work as defined in code.
<div class="row" ng-controller="RegionController">
<div class="col-lg-12" >
<div class="hpanel">
<div class="panel-heading">
<!-- <div panel-tools></div> -->
<h2>Region Master Entry</h2>
</div>
<div class="panel-body">
<!--change form name,and submit controller name-->
<form role="form">
<div class="form-group">
<label class="col-sm-2 control-label">Region Name</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region name" class="form-control m-b" required name="Region Name" ng-model="formRegionData.region_name" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Region Code</label>
<div class="col-sm-10">
<input type="text" placeholder="please enter Region code" class="form-control m-b" required name="Region Code" ng-model="formRegionData.region_code">
</div>
</div>
<div class="form-group">
<div class="col-sm-3">
<label>Active</label>
</div>
<div class="checkbox checkbox-success col-sm-9">
<input id="checkbox3" type="checkbox" checked="" ng-model="formRegionData.status">
<label for="checkbox3">
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-8">
<button class="btn btn-sm btn-primary btn-xl text-right" type="submit" ng-click="createRegion()"><strong> Save Region </strong></button>
</div>
</div>
{{formRegionData | json}}
</form>
</div>
</div>
</div>
</div>
"{{formRegionData | json}}" this will return in HTML input text result of but not send data to the controller
in Controller the code is written as
.controller('RegionController', function( $scope , regionService) {
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
console.log(formRegionData);
regionService.SaveRegion( formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
})
and my service to work according to Controller
.factory('regionService',function($http ){
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});

You have missed $scope
$scope.createRegion = function() {
debugger;
$scope.processing = true;
$scope.message = '';
console.log($scope.formRegionData);
regionService.SaveRegion($scope.formRegionData )
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
$scope.processing = false;
$scope.storyData = {};
$scope.message = data.message;
});
}
})
and remove ng-click="createRegion()" in your button control and add this code in your form tag by ng-submit. like,
<form ng-submit="createRegion()" role="form">

You have missed of $scope in form region data
Here is the link Jsfiddle
JS
angular.module('myApp', ['ngStorage'])
.controller('RegionController', function($scope, regionService) {
var vm = this;
$scope.createRegion = function() {
debugger;
vm.processing = true;
vm.message = '';
regionService.SaveRegion($scope.formRegionData)
.then(function(data) {
debugger;
//console.log(data);
//.success(function(data) {
vm.processing = false;
vm.storyData = {};
vm.message = data.message;
});
}
}).factory('regionService', function($http) {
var regionFactory = {};
regionFactory.SaveRegion = function(formRegionData) {
debugger;
return $http.post('/api/region/', formRegionData);
}
return regionFactory;
});

Related

AngularJs hide all alerts: Uncaught SyntaxError

I have an angularJS component that displays alerts when something goes wrong while submitting, these alerts are not auto dismissed by design.
But, when the user fix all errors (there can be many alerts displayed on the screen) and submit I want to dismiss these alerts.
Based on this example https://jsfiddle.net/uberspeck/j46Yh/
I did something like this:
(function(){
var mainApp = angular.module("myApp");
function AlertsCtrl($scope, alertsManager) {
$scope.alerts = alertsManager.alerts;
}
mainApp.factory('alertsManager', function() {
return {
alerts: {},
addAlert: function(message, type) {
this.alerts[type] = this.alerts[type] || [];
this.alerts[type].push(message);
},
clearAlerts: function() {
for(var x in this.alerts) {
delete this.alerts[x];
}
}
};
mainApp.controller("addUserCtrl", ['Restangular', 'alertsManager', '$alert', 'roles', '$window' , function(Restangular, alertsManager, $alert, roles, $window) {
var that = this;
init();
that.submit = function() {
var data = {
user : that.name,
role : that.role.serverName,
credentials : that.password1
}
Restangular.all("admin").all("user").all("add").post(data).then(function() {
//$alert({title: 'Add User:', content: 'Completed succefully', type: 'success', container: '#alert', duration: 5, show: true});
alertsManager.addAlert('Completed succefully', 'alert-success');
init();
alertsManager.clearAlerts();
}, function(reason) {
//$alerts{title: 'Add User:', content: reason.data.error, type: 'danger', container: '#alert', show: true});
alertsManager.addAlert(reason.data.error, 'alert-error');
});
}
function init() {
that.name = "";
that.roles = roles;
that.role = that.roles[0];
that.password1 = "";
that.password2 = "";
}
}]);
})();
HTML:
<div ng-controller="addUserCtrl as ctrl">
<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<form class="form-horizontal" ng-submit="ctrl.submit()">
<div class="panel-heading">Add User</div>
<div class="panel-body">
<div class="form-group">
<label for="name" class="col-sm-3 control-label">User Name: <span class="required">*</span></label>
<div class="col-sm-8">
<input type="text" class="form-control" id="name" ng-model="ctrl.name"></input>
</div>
</div>
<div class="form-group">
<label for="role" class="col-sm-3 control-label">Role: <span class="required">*</span></label>
<div class="col-sm-8">
<select class="form-control" id="role" ng-model="ctrl.role" ng-options="opt.displayName for opt in ctrl.roles"></select>
</div>
</div>
<div class="form-group">
<label for="password1" class="col-sm-3 control-label">Password: <span class="required">*</span></label>
<div class="col-sm-8">
<input type="password" class="form-control" id="password1" ng-model="ctrl.password1"></input>
</div>
</div>
<div class="form-group">
<label for="password2" class="col-sm-3 control-label">Re-enter Password: <span class="required">*</span></label>
<div class="col-sm-8" ng-class="{'has-error' : ctrl.password1 != ctrl.password2}">
<input type="password" class="form-control" id="password2" ng-model="ctrl.password2"></input>
<p class="help-block" ng-if="ctrl.password1 != ctrl.password2">Passwords don't match</p>
</div>
</div>
</div>
<div class="panel-footer">
<button type="submit" class="btn btn-default" ng-disabled="!ctrl.name || !ctrl.password1 || !ctrl.password2 || ctrl.password1 != ctrl.password2">OK</button>
</div>
<div ng-controller="AlertsCtrl">
<div ng-repeat="(key,val) in alerts" class="alert {{key}}">
<div ng-repeat="msg in val">{{msg}}</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
But I'm getting:
Uncaught SyntaxError: Unexpected end of input
angular.js:14747 Error: [ng:areq] http://errors.angularjs.org/1.4.3/ng/areq?p0=addUserCtrl&p1=not%20aNaNunction%2C%20got%20undefined
You did not complete all brackets correctly.
Below should be like this:
mainApp.factory('alertsManager', function() {
return {
alerts: {},
addAlert: function(message, type) {
this.alerts[type] = this.alerts[type] || [];
this.alerts[type].push(message);
},
clearAlerts: function() {
for(var x in this.alerts) {
delete this.alerts[x];
}
}
}
});
You forgot to complete the factory by });.
And that is why indentation is so important.
Hope this may help you.

ng-click exec function on controllers twice

HTML
<form id="newSaveForm">
<div class="item">
<div class="list">
<label class="item item-input">
<input type="date" ng-model="dateSave" placeholder="Date" required>
</label>
</div>
<div class="list">
<label class="item item-input">
<input type="number" ng-model="moneySave" placeholder="Deposit?" required>
</label>
</div>
<button class="button button-block button-balanced ion-android-checkbox-outline" data-ng-click="addMoney(dateSave,moneySave)" ng-disabled="buttonDisabled"> Save </button>
</div>
</form>
JavaScript
.controller('saveCtrl', function($scope, $state, $http, $filter) {
getAll();
$scope.addMoney = function(tgl, jml) {
$scope.buttonDisabled = true;
$http.post("http://localhost/mymoney/insert.php?jml=" + jml + "&tgl=" + conv_date(tgl)).success(function(response) {
getAll();
$scope.dateSave = "";
$scope.moneySave = "";
console.log('Success Insert');
}).finally(function() {
$scope.buttonDisabled = false;
});
};
function getAll() {
$http.get("http://localhost/mymoney/deposit.php")
.then(function(response) {
$scope.listDeposit = response.data.records;
});
};
function conv_date(tgl) {
return $filter('date')(tgl, 'yyyy-MM-dd');
};
});
Why when I click addMoney function twice I get 2 results in one time

Cannot call another function from within scope onSubmit function

I have a very simple form template and controller. But i'm unable to call a function from within the onSubmit scope function. Controller is:
angular
.module('myApp')
.controller('registerUserCtrl', registerUserCtrl);
function registerUserCtrl($scope, $location, $window, authenticationService, $http, vcRecaptchaService){
$scope.pageHeader = {
title: 'Register',
};
$scope.register = function (data) {
console.log('in scope.register ');
userService.register(data)
.success(function(data) {
console.log('setting to true.....');
authenticationService.isLoggedIn = true;
authenticationService.user = data.user;
authenticationService.token = data.token;
$location.path("/");
}).error(function(status, data) {
console.log(status);
console.log(data);
$scope.formError = "This email has already been taken";
});
}
$scope.onSubmit = function () {
console.log('in onSubmit');
//N.B. Need to veriify this
var response = vcRecaptchaService.getResponse();
$scope.formError = "";
if(!$scope.formData || !$scope.formData.email || !$scope.formData.password) {
$scope.formError = "All fields required, please try again";
return false;
} else {
console.log('$scope is ');
console.log($scope);
$scope.register($scope.formData);
}
};
}
And template is:
<div id="register-wrapper">
<form class="form-horizontal" role="form" ng-submit="onSubmit()">
<div role="alert" ng-show="formError" class="alert alert-danger">{{ formError }}</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-4 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" ng-model="formData.email">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-4 control-label">Password</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" ng-model="formData.password">
</div>
</div>
<div vc-recaptcha key="'6Lf6aQsTAAAAAACdCxN2FqHHKpz0RyF9jMJsn6h4'"></div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-10">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
I always end up with:
undefined is not a function
at the $scope.register($scope.formData); line. I've done this many times before, but somehow now its not working...
You need to inject userSevice in your controller as dependency
angular
.module('myApp')
.controller('registerUserCtrl', registerUserCtrl);
function registerUserCtrl($scope, $location, $window, authenticationService,
$http, vcRecaptchaService, userSevice)
{

Firebase angularfire child.$asObject give properties undefined

I've got this code:
factory
app.factory('Items', function($firebase,FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var items = $firebase(ref.child('items')).$asArray();
var Item = {
all: function () {
return items;
},
create: function (item) {
return items.$add(item);
},
get: function (itemId) {
return $firebase(ref.child('items').child(itemId)).$asObject();
},
update: function (itemId, item) {
return $firebase(ref.child('items').child(itemId)).update(item);
},
delete: function (item) {
return items.$remove(item);
}
};
return Item;
});
route
app.config(function($stateProvider) {
$stateProvider
.state('items_update', {
url: '/items/update/:id',
templateUrl: 'views/items/form.html',
controller:'ItemsUpdateController',
resolve:{
item:function(Items,$stateParams){
return Items.get($stateParams.id);
}
}
})
});
controller
app.controller('ItemsUpdateController', function ($scope, item, $state) {
$scope.item = item;
console.log($scope.item.url);
$scope.add = function() {
Items.update($scope.item).then(function () {
$state.transitionTo('items');
});
}
});
why console.log($scope.item.url); give me undefined ?
but in the view I've got all the data
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()">
<div class="form-group">
<input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback />
</div>
<div class="form-group">
<input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback />
</div>
<div class="form-group">
<input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback />
</div>
<div class="form-group">
<button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button>
<input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" />
</div>
<div class="form-group form-no-required clearfix">
<div class="pull-right">
<button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button>
</div>
</div>
</form>
ENDS UP
as in the #Frank van Puffelen comment
I worked it out with:
app.controller('ItemsUpdateController', function($scope, item, $state) {
item.$loaded().then(function(data) {
$scope.item = data;
console.log($scope.item.url);
});
$scope.add = function() {
Items.update($scope.item).then(function() {
$state.transitionTo('items');
});
}
});
This is because by the time your console.log($scope.item.url); runs, the data hasn't been loaded from Firebase yet. Angular listens for a notification from Firebase/AngularFire to know when the data has loaded and then updates the view.
Also see angularfire - why can't I loop over array returned by $asArray? and Trying to get child records from Firebase.

AngularJS select not updating after json push

I have the following controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
$scope.userName = '';
//$apply();
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
And the following HTML:
<h2>Users</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
When I add a user in the addUser() function I can see the user is added since it's listed under the ng-repeat, however the user name does not appear in the select box.
This is because you use the same controller twice. This creates two separate scopes. When you add a user in one scope it doesn't get added in the second scope. The fix is simple, join the code in one scope:
<div ng-controller="userControl">
<h2>Users</h2>
<div>
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div>
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
</div>
An alternative approach is to create a Service since services are singletons:
module.factory('Users',function(){
var users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
];
return {
users:users,
add:function(user){
users.push(user);
}
}
});
function userControl($scope, Users) {
$scope.users = Users.users;
$scope.addUser = function() {
var nextid = $scope.getNextId();
Users.add({id:nextid,name:$scope.userName});
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
This will work with your original markup.

Resources