Get value from HTML page to angularJS file - angularjs

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');
}

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">

Dynamically adding multiple custom directives associated with single controller in angularjs 1

I have an html template attached to a controller and three directives. There are three buttons. On clicking a button a directive is added to the page(using ng-click) like this(the following is in my controller not in directive):
$scope.addFilterDimension = function() {
console.log('CLICKED!!!!!!!')
var divElement = angular.element(document.querySelector('#filterDimension'));
var appendHtml = $compile('<filter-directive></filter-directive>')($scope);
divElement.append(appendHtml);
}
Similarly for other buttons, other directives are added. Now, I can keep adding as many of these directives as I like, which is the use case here.
These directives are basically like forms containing either dropdowns, input boxes or both. The values user selects from the dropdowns or enters in input boxes have to be sent back to the backend to be stored in the DB.
This is one of the directives(others are very similar):
anomalyApp.directive('filterDirective', function() {
return {
restrict: "E",
scope: {},
templateUrl:'filter-dimension.html',
controller: function($rootScope, $scope, $element) {
$scope.dimensionsOld = $rootScope.dimensionsOld;
$scope.dimensions = $rootScope.dimensions;
$scope.selectedDimensionName = $rootScope.selectedDimensionName;
$scope.selectedDimensionValue = $rootScope.selectedDimensionValue;
$scope.extend = $rootScope.extend;
$scope.selectedExtend = $rootScope.selectedExtend;
$scope.isDateField = $rootScope.isDateField;
console.log($scope.dimensions);
$scope.Delete = function(e) {
//remove element and also destoy the scope that element
$element.remove();
$scope.$destroy();
}
}
}
});
Now, in my controller I assign $rootscope to my values which have to be used in the directives and thus catch them in the directive. Example:
$rootScope.dimensions = temp.map(d=>d.dimName);
$rootScope.selectedDimensionName = '';
$rootScope.selectedDimensionValue = '';
And this is how I retrieve my values from added directives:
var retriveValue = function() {
var filtersData = [];
var constraintsData = [];
var variablesData = [];
var ChildHeads = [$scope.$$childHead];
var currentScope;
while (ChildHeads.length) {
currentScope = ChildHeads.shift();
while (currentScope) {
if (currentScope.dimensions !== undefined){
filtersData.push({
filterDimensionName: currentScope.selectedDimensionName,
filterDimensionValue: currentScope.selectedDimensionValue,
filterDimensionExtend: currentScope.selectedExtend,
filterDimensionIsDateFiled: currentScope.isDateField
});
}
if (currentScope.constraintDimensions !== undefined){
filtersData.push({
constraintDimensionName: currentScope.selectedConstraintName,
constraintDimensionValue: currentScope.selectedConstraintValue,
constraintDimensionExtend: currentScope.selectedConstraintExtend,
constraintDimensionVariable: currentScope.selectedConstraintVariable,
constraintDimensionOperator: currentScope.selectedOperator,
constraintDimensionVariableValue: currentScope.constraintVariableValue,
constraintDimensionIsDateField: currentScope.isDateFieldConstraint
});
}
if (currentScope.variableNames !== undefined){
console.log('currentScope.selectedVariableVariable',currentScope.selectedVariableVariable);
filtersData.push({
variableName: currentScope.selectedVariableVariable,
variableOperator: currentScope.selectedVariableOperator,
variableValue: currentScope.variableVariableValue,
variableExtend: currentScope.selectedVariableExtend
});
}
currentScope = currentScope.$$nextSibling;
}
}
return filtersData;
}
This is one of the directive's template:
<div >
<div>
<label>Dimension</label>
<select class = "custom-select custom-select-lg mb-6" ng-model="selectedDimensionName" ng-options="dimension for dimension in dimensions">
<!-- <option ng-repeat="table in tables track by $index">{{table}}</option> -->
</select>
</div>
<div>
<label>Date Field</label>
<input type="checkbox" ng-model="isDateField">
</div>
<div>
<label>Value</label>
<select multiple class = "custom-select custom-select-lg mb-6" ng-model="selectedDimensionValue" ng-options="val for val in ((dimensionsOld | filter:{'dimName':selectedDimensionName})[0].dimValues)"></select>
</span>
</div>
<div>
<label>Extend</label>
<select class = "custom-select custom-select-lg mb-6" ng-model="selectedExtend" ng-options="val for val in extend"></select>
</span>
</div>
<button type="button" class="btn btn-danger btn-lg" ng-click="Delete($event)">Delete</button>
This is in the main html to add the directive:
<div id="filterDimension"> </div>
I know this is not a good way, but please suggest a better one.
Secondly, a new change has to be made where inside one of the directives there will be a button, clicking on which 2 dropdowns(or simply one more directive) will be added and can be added as many times as needed(just like the other directive).
The issue here is this one is a directive inside another directive and I am facing unusual behavior like:
When I add the parent directive it is fine, I add the child directives its fine, but when I add a second parent and try to add its child, they get appended inside the first directive.
Even if I somehow manage to get out of the above point I do not know how to retrieve values from such directives.
PS: I am new in AngularJS or front-end for that matter, the retriveValue() and using rootscope I got from somewhere online.

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>

AngularJS: Shows reference error : goToFormDashboard not defined in scope

I am trying to call a function on onchange event but getting reference error everytime for that function my fromtend code is this:
<label class="item item-input item-select" ng-controller="manageTeam">
<div class="input-label">
Select Form
</div>
<select onchange="goToFormDashboard($(this).children(':selected').val())" ng-model="Formname" ng-options="f.Formname for f in forms track by f.Formid"></select>
</label>
My controller is this:
.controller('manageTeam', function($scope, $ionicLoading, $http, $timeout, $rootScope, $state) {
$scope.goToFormDashboard = function (formId) {
$ionicLoading.show({template: 'Loading'});
$timeout(function () {
$ionicLoading.hide();
}, 1500);
var formID = formId;
$scope.form.length = 0;
.....
is something missing in that?
You need to use ng-change directive & no need to use jquery here you can get the value inside ng-model, Formname contains whole object you can pass form id only by doing Formname.Formid to goToFormDashboard method.
Markup
<select ng-change="goToFormDashboard(Formname.Formid)" ng-model="Formname"
ng-options="f.Formname for f in forms track by f.Formid"></select>
In JavaScript "this" means the function, from which the actual method was called. Example:
var myObject = function();
myObject.prototype.testvar = "hello world";
myObject.prototype.test = function(){
return this.testvar;
}
var obj = new myObject();
console.log(obj.test());
this would display "hello world" in your chrome console. You dont need to pass the dropdown's value to the submit handler. just have a look at
Angular JS: Pass a form's select option value as parameter on ng-submit="doStuff()"
this is exactly what you are searching for

Angular.js. Two-way data binding breaks when using services

The problem is that SecondName attribute is not updating when I input text in the field.
please look at this code at jsfiddle: http://jsfiddle.net/HEdJF/253/
HTML:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<div>
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>FirstName is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
<hr>
<div ng-controller="SecondCtrl as Second">
SecondName: {{Second.Data.SecondName}}<!-- How do I automatically updated it here? -->
</div>
</div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.service('Data', function(){
var obj;
return obj = { FirstName: '54',
SecondName: '22',
f: function(){
obj.FirstName = '1';
obj.SecondName = obj.FirstName;
}
};
});
myApp.controller('FirstCtrl', function( $scope, Data ){
Data.f();
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function( Data ){
Second = this;
Second.Data = Data;
});
It's not going to work like you think it should. This line:
obj.SecondName = obj.FirstName;
creates a new property SecondName equal by value to the FirstName. However since both properties are primitive types (String) there is no connection between them. In other words obj.SecondName does not reference obj.FirstName.
You have two options.
Option 1. (bad) Set up additional watcher on FirstName change, and once that happens update SecondName respectively
$scope.$watch('Data.FirstName', function() { Data.SecondName = Data.FirstName; });
http://jsfiddle.net/HEdJF/254/
Option 2. Don't introduce additional watchers and change your architecture. For example, use FirstName in the second controller too, since they are supposed to be equal.
http://jsfiddle.net/HEdJF/255/
This is a scoping issue because of your nested scopes. Take a look at this website for a clear explanation: http://toddmotto.com/digging-into-angulars-controller-as-syntax/. There's a few different solutions to solve your problem under the Nested Scopes section.
The problem with your code is that the First Controller is just changing the value of Data.FirstName object, hence the changes are not reflecting on your second controller because the value of SecondName does not change after it is initialized in the first controller. So you have to set your Data.SecondName
in your data as well.
Alternatively, you can do this.
<div>
<input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
<br>FirstName is : <strong>{{Data.SecondName=Data.FirstName}}</strong><!-- Successfully updates here -->
</div>
You can also use directives to achieve this functionality, but I guess you are just looking for the above solution.
Cheers!

Resources