Get values into edit form angular - angularjs

Inside main.view.html I have button Edit:
<md-button class="md-raised md-primary" ng-click="redirectEdit($index)" >Edit</md-button> which has redirectEdit($index) so it takes index of current line (to have values) in main.controller.js it looks like:
$scope.redirectEdit = function(index){
$scope.all[index];
window.location = "../ang/#!/edit";
$scope.name =$scope.all[index].name;
$scope.surname =$scope.all[index].surname;
$scope.email =$scope.all[index].email;
$scope.review =$scope.all[index].review;
};
with this method I want to redirect user to Edit form And have these specific taken entered into input fields.
First Name: <input type="text" ng-model="name" >
I tried doing it like this but that doesn't work

Looking at your scenario, i would suggest you to use $emit and $on.Also make a object of all fields like $scope.formFields = {};
$scope.redirectEdit = function(index){
$scope.all[index];
$scope.formFields = {};
$scope.formFields.name =$scope.all[index].name;
$scope.formFields.surname =$scope.all[index].surname;
$scope.formFields.email =$scope.all[index].email;
$scope.formFields.review =$scope.all[index].review;
$scope.$emit('userData', {data: $scope.formFields}); //to set the value
window.location = "../ang/#!/edit";
};
And on editController.js get the data and accordingly assign values to ng-model
$rootScope.$on('userData', function (event, data) {}); // to get the value
I hope this helps

Related

AngularJS - How to pass data from View (HTML) to Controller (JS)

I am really new to AngularJS. I want to pass some object from View (HTML) to my controller (JS).
Actually my Client will send me data in HTML and I have to take that data and process that data in my controller and then display the processed output on screen. He will be using some back-end technology called ServiceNow - https://www.servicenow.com/ .
All the solutions I saw had some event like click event or change event, but in my case this has to be done on page load.
I m using Input type hidden for passing the data to the controller, seems like it's not working.
So is there any other way I can do this ?
Here's the code I am trying to use
<div ng-controller="progressController" >
<input type="hidden" value="ABCD" ng-model="testingmodel.testing">
</div>
app.controller('progressController', function($scope) {
console.log($scope.testingmodel.testing);
});
It says undefined when I console.log my variable in Controller.
You're doing console.log(...) too early. At this time your controller doesn't have any information from the view.
The second problem is that you're binding the view to a variable in controller and not the other way around. Your $scope.testingmodel.testing is undefined and it will obviously the value in the view to undefined.
Solution
Use ng-init to initialize the model and the controller's hook $postLink to get the value after everything has been initialized.
Like this
<div ng-controller="progressController" >
<input type="hidden" ng-model="testingmodel.testing" ng-init="testingmodel.testing = 'ABCD'">
</div>
app.controller('progressController', function($scope) {
var $ctrl = this;
$ctrl.$postLink = function() {
console.log($scope.testingmodel.testing);
};
});
Edit: extra tip
I don't recomment using $scope for storing data since it makes the migration to newer angular more difficult.
Use controller instead.
Something like this:
<div ng-controller="progressController as $ctrl" >
<input type="hidden" ng-model="$ctrl.testingmodel.testing" ng-init="$ctrl.testingmodel.testing = 'ABCD'">
</div>
app.controller('progressController', function() {
var $ctrl = this;
$ctrl.$postLink = function() {
console.log($ctrl.testingmodel.testing);
};
});
You should use the ng-change or $watch
<div ng-controller="progressController" >
<input type="hidden" value="ABCD" ng-model="testingmodel.testing" ng-change="change()">
</div>
app.controller('progressController', function($scope) {
$scope.change = function(){
console.log($scope.testingmodel.testing);
}
});
Or:
app.controller('progressController', function($scope) {
$scope.$watch('testingmodel.testing', function(newValue, olValue){
console.log(newValue);
}
});
If you use ng-change, the function is only called if the user changes the value in UI.
If you use $watch anyway, the function is called.
You can't use value attribute for set or get value of any control, angularJS use ngModel for set or get values.
Here You should try like this way
app.controller('progressController', function($scope) {
//from here you can set value of your input
$scope.setValue = function(){
$scope.testingmodel = {}
$scope.testingmodel.testing = 'ABCD';
}
//From here you can get you value
$scope.getValue = function(){
console.log($scope.testingmodel.testing);
}
});
if you want to bind from html side then you should try like below
<input type="text" ng-model="testingmodel.testing">
<input type="hidden" ng-model="testingmodel.testing">

Angular: how to save edited values?

here is my plnkr
http://plnkr.co/edit/0W1SZll1BOK5uuEtdycy?p=preview
im trying to save edited values from my edit contact modal.
here is a edit method that takes current value from object:
$scope.edit = function(terminal) {
$scope.name = terminal.name;
$scope.last = terminal.last;
$scope.age = terminal.age;
}
i read about angular copy, there is anything else?
any one can help me please ill glat to learn how to do that
Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.
Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object. Your JS will look like this:
$scope.edit = function(terminal) {
$scope.name = angular.copy(terminal.name);
$scope.last = angular.copy(terminal.last);
$scope.age = angular.copy(terminal.age);
}
You are creating a lot of extra manual work by not using one object in ng-model in the first place instead of using individual scope properties.
There is a golden rule also that if you don't have a dot in ng-model you are doing it wrong
Do something like:
<input ng-model="terminal.name">
<input ng-model="terminal.age">
Then work along the following lines:
$scope.edit = function(terminal) {
// store reference to terminal being edited
$scope.currentTerminal = terminal;
// make a copy so live one is not affected -- will be used in form
$scope.terminal = angular.copy(terminal);
}
$scope.save = function(){
// update stored original with changes
angular.extend($scope.currentTerminal, $scope.terminal);
// reset terminal used in form
$scope.terminal ={};
}
I would strongly suggest you get rid of jQuery and bootstrap.js and use angular-ui-bootstrap insted
You need to pass the index of the row that you are going to edit. pass the index when you click on edit button.
Change in script.js
$scope.edit = function(terminal,index) {
$scope.name = terminal.name;
$scope.last = terminal.last;
$scope.age = terminal.age;
$scope.edit_index = index
}
$scope.saveEdit =function(){
index = $scope.edit_index
$scope.terminals[index].name = $scope.name;
}
Change in index.html
<td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editModalLong" ng-click="edit(terminal,$index)">Edit</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="saveEdit()">Save</button>
http://plnkr.co/edit/GpVB2dUiHCY6NslQDuBe?p=preview

ng-init does not initialize my selected model

I have a select option where I get a list of titles i.e. Mr, Mrs, Dr etc. from an API, the code looks like this in the front end:
<select class="form-control" name="titleSelect" id="titleSelect" ng-options="option.value for option in titleData.availableOptions track by option.key" ng-model="adult[$index].selectedTitle" ng-init="adult[$index].selectedTitle = titleData.availableOptions[0]"></select>
And this in the controller:
var getPassengerTitle = PassengerDetailsAndCardDetailsService.getPassengerTitle();
PassengerDetailsAndCardDetailsService is service, where I get the API data i.e. the title data. Furthermore this service returns a promise.
This is where I set the title Data:
getPassengerTitle.then(function(result){
$scope.availableTitles = angular.fromJson(result.titleList);
$scope.tempListOfTitles = [];
for(var key in $scope.availableTitles){
$scope.tempListOfTitles.push({key : key, value : $scope.availableTitles[key]});
};
$scope.titleData = {
availableOptions: $scope.tempListOfTitles,
};
});
When I try to ng-init to the first option (that is Mr.) it does not work as in a blank option is shown. However when I tried statically defining the titleData in an object it works, could you please help me?
UPDATE:
I failed to mention that the title data is inside an ng-repeat to support input for multiple people/passengers in this case. Therefore I'm using adult[$index] where it creates an ng-model for each person/passenger.
I am not sure if this is the required behavior you want, but if you want to initialise the title on selecting an option you can either use the value from ng-model or use the event handler ng-change. Here is an example jsbin which handles the change and assigns the new value to ng-model. Let me know if this is what you were looking for
try like this.
var myapp = angular.module('app', []);
myapp.controller('Main', function ($scope) {
var vm = this;
vm.adult = {
'selectedTitle':'1'
};
vm.titleData = [
{'key':'0','value':'Mr'},
{'key':'1','value':'Ms'},
{'key':'2','value':'Dr'}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app">
<div ng-controller="Main as ctrl">
<div class="select-style">
<select ng-options="option.key as option.value for option in ctrl.titleData" ng-model="ctrl.adult.selectedTitle"></select>
</div>
</div>
</div>

Disable Text Entry - angular with jquery

Found these perfect solution here: Example
// Catch all events related to changes
$('#textbox').on('change keyup', function () {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
// Update value
$(this).val(sanitized);
});
HTML
<input type="text" id="textbox" />
but i can't make this work inside a controller.
How can it be done?
One thing that you can do is use ng-change in your input like this:
<div ng-controller="yourCtrl as ctrl">
<input type="text" id="textbox" ng-change="ctrl.doSomething()" ng-model="ctrl.someVar">
</div>
in this way you will have access to the value of the input inside your controller that can be like this:
angular.module('yourModule').controller('yourCtrl',[function(){
var self = this;
self.doSomething = function(){
//you can access the value of the input using
// self.someVar
}
});
The ng-change (official doc: https://docs.angularjs.org/api/ng/input/input%5Btext%5D ) is "executed when input changes due to user interaction with the input element".
You can also use the ngKeyup (official doc: https://docs.angularjs.org/api/ng/directive/ngKeyup ) that is "evaluated upon keyup" how you connect it to a function is the same as ng-change. You will have only to choose one of the two.

Get value from HTML page to angularJS file

I tried to get the HTML page value to angularJS function , The below steps are which i tried.
HTML page :
<label class="item-input item-stacked-label">
<span class="input-label cont_det_label">First Name</span>
<p class="contact_display" id="txtFirstName" ng-model="testName">Satya</p>
</label>
angularJS Page :
.controller('SocialNetworkCtrl', ['$scope','$http','$state','ContactsService','$ionicNavBarDelegate','$ionicLoading','$ionicPopup',function($scope, $http, $state, ContactsService, $ionicNavBarDelegate, $ionicLoading,$ionicPopup) {
$scope.showUserProfile = function() {
$state.go("linkedin");
var firstname = (document.getElementById("txtFirstName").value);
}
}])
So I need var firstname = Satya ?? Is it correct way please guide me to access this value .
var firstName = $scope.testName
<input ng-model="testName" />
testName is the ng-model name that you have give. It will be automatically binded to your controller. No need the get the value using document.getElementById
Wrong usage , why ng-model in <p> tag??
Update
Change your fiddle with the following code, it will work. Also make sure framework is selected properly (as in the image)
<div ng-app ng-controller="testController">
<input ng-model="testDataName" ng-change="check()" /> {{testDataName}}
After ng-change : {{checkName}}
</div>
function testController($scope) {
$scope.testDataName="Dummy Name";
$scope.check = function () {
$scope.checkName=$scope.testDataName;
console.log($scope.checkName);
};
}
its a text node, you will require .innerHTML or '.innerText', .value is for form inputs
var firstname = (document.getElementById("txtFirstName").innerHTML);
and don't use ng-model on a p element, change it to like this
<p class="contact_display" id="txtFirstName">{{testName}}</p>
just use $scope.testName to get the value, no need for firstname = (document.getElementById("txtFirstName").innerHTML); querying DOM for value is jQuery style, use angular the $scope for 2 way bindings
Read more at official doc
Update here is updated function on loginCtrl
.controller('loginCtrl', ['$scope', function ($scope) {
$scope.testNameData = 'Satya';
$scope.doLogin = function() {
alert($scope.testNameData);
};
}])
If you really want to go jQuery way here is what you can do, its not recommended, you should use angular directive to do DOM manipulation
$scope.showUserPro = function() {
$ionicLoading.show();
// Here i need the value of <p tag>
var name = document.getElementById("txtFirstName"),
firstNameFromHtmlPtag = name.innerText;
console.log(firstNameFromHtmlPtag, 'Doing API Call 1');
}

Resources