angularjs fetch value from textbox after clicking a button only - angularjs

This is my code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('myController', function ($scope) {
$scope.getName = function () {
$scope.name = fname;
$scope.lastName = lastName;
};
})
</script>
</head>
<body ng-app="myApp" >
<div >
<input type="text" ng-model="name"/> <br>
<input type="text" ng-model="lastName" />
</div>
<div ng-controller="myController">
<input type="button" value="click" ng-click="getName()" />
<br>
Hello FirstName {{name}}<br>
Last Name {{lastName}}
</div>
</body>
</html>
values are coming while typing into textbox but i want values only after clicking the button.Please help me.
I tried in both ways simple as well as by using service or factory method but no success

You must separate the ng-models of the input texts and destination field. They are updating real-time because of having the same models.
I have created the correct version for you:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('myController', function ($scope) {
$scope.getName = function () {
$scope.nameToSet = $scope.name;
$scope.lastNameToSet = $scope.lastName;
};
})
</script>
</head>
<body ng-app="myApp" >
<div >
<input type="text" ng-model="name"/> <br>
<input type="text" ng-model="lastName" />
</div>
<div ng-controller="myController">
<input type="button" value="click" ng-click="getName()" />
<br>
Hello FirstName {{nameToSet}}<br>
Last Name {{lastNameToSet}}
</div>
</body>
</html>
UPDATE: Here is another version with using a factory:
var myApp = angular.module('myApp', []);
myApp.factory('container', function() {
var model = {
name: '',
lastName: ''
};
return {
model: model,
setName: function(nameToSet) {
model.name = nameToSet;
},
setLastName: function(lastNameToSet) {
model.lastName = lastNameToSet;
}
};
});
myApp.controller('myController', function ($scope, container) {
$scope.$watch('name', function(newvalue,oldvalue) {
container.setName(newvalue);
});
$scope.$watch('lastName', function(newvalue,oldvalue) {
container.setLastName(newvalue);
});
$scope.onNameType = function(value) {
container.setName(value);
};
$scope.onLastNameType = function(value) {
container.setLastName(value);
};
$scope.getName = function () {
debugger;
$scope.nameToSet = container.model.name;
$scope.lastNameToSet = container.model.lastName;
};
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body ng-app="myApp" >
<div >
<input type="text" ng-model="name" ng-change="onNameType(name)"/> <br>
<input type="text" ng-model="lastName" ng-change="onLastNameType(lastName)" />
</div>
<div ng-controller="myController">
<input type="button" value="click" ng-click="getName()" />
<br>
Hello FirstName {{nameToSet}}<br>
Last Name {{lastNameToSet}}
</div>
</body>
</html>

Related

Manual bootstrapping and Data Sharing in b/w controllers through angular service

I am trying to share data in b/w controllers through angular service.
It worked perfectly fine if i let my app to bootrap automatically.
But when i manually bootstrap part of my HTML with same app, Data sharing between controllers do not work as expected.
Attached herewith is the fiddle and plnckr.
plnckr with auto bootstrap
plnckr with manual bootstrap
Following is the working code of data sharing b/w controllers through service/factory using auto bootstrap
// Code goes here
// Code goes here
// Code goes here
(function() {
'use strict';
var app = angular.module('myApp', []);
app.factory('MyFactory', function() {
var myFactory = {};
myFactory.myProperty = {prop: 'Hello'};
myFactory.setProperty = function(value) {
this.myProperty.prop = value;
};
return myFactory;
});
app.service('MyService', function() {
this.myProperty = {prop: 'Test'};
this.setProperty = function(value) {
this.myProperty.prop = value;
}
});
app.controller('DummyController', DummyController);
DummyController.$Inject = ['$scope', 'MyFactory', 'MyService'];
app.controller('Dummy1Controller', Dummy1Controller);
Dummy1Controller.$Inject = ['$scope', 'MyFactory', 'MyService'];
function DummyController($scope, MyFactory, MyService) {
$scope.property = MyFactory.myProperty;
$scope.property1 = MyService.myProperty;
}
function Dummy1Controller($scope, MyFactory, MyService) {
MyFactory.setProperty('World1144');
$scope.property = MyFactory.myProperty;
MyService.setProperty('World1144');
$scope.property1 = MyService.myProperty;
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="script.js"></script>
</head>
<body ng-app='myApp'>
<div class="container-fluid">
<br />
<div class="row">
<div class="col-md-6">
<div class="panel-group">
<div class="panel panel-primary">
<div class="panel-heading">Example [As a Service]</div>
<div class="panel-body">
<div ng-controller='DummyController' class='col-md-6'>
<form class="form-inline" role="form">
DummyController
<div>
Current Factory Value :
<input type='text' ng-model='property.prop'>
<br> Current Service Value :
<input type='text' ng-model='property1.prop'>
</div>
</form>
</div>
<hr>
<div ng-controller='Dummy1Controller' class='col-md-6'>
<form class="form-inline" role="form">
Dummy1Controller
<div>
Current Factory Value :
<input type='text' ng-model='property.prop'>
<br> Current Service Value :
<input type='text' ng-model='property1.prop'>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Following is the code of data sharing b/w controllers through service using manual bootstrap
// Code goes here
// Code goes here
// Code goes here
(function() {
'use strict';
var app = angular.module('myApp', []);
app.factory('MyFactory', function() {
var myFactory = {};
myFactory.myProperty = {prop: 'Hello'};
myFactory.setProperty = function(value) {
this.myProperty.prop = value;
};
return myFactory;
});
app.service('MyService', function() {
this.myProperty = {prop: 'Test'};
this.setProperty = function(value) {
this.myProperty.prop = value;
}
});
app.controller('DummyController', DummyController);
DummyController.$Inject = ['$scope', 'MyFactory', 'MyService'];
app.controller('Dummy1Controller', Dummy1Controller);
Dummy1Controller.$Inject = ['$scope', 'MyFactory', 'MyService'];
function DummyController($scope, MyFactory, MyService) {
$scope.property = MyFactory.myProperty;
$scope.property1 = MyService.myProperty;
}
function Dummy1Controller($scope, MyFactory, MyService) {
MyFactory.setProperty('World1144');
$scope.property = MyFactory.myProperty;
MyService.setProperty('World1144');
$scope.property1 = MyService.myProperty;
}
})();
setTimeout(function(){
angular.bootstrap(document.querySelector(".c1"), ["myApp"])//manual bootstrapping of PaginationComp
angular.bootstrap(document.querySelector(".c2"), ["myApp"])
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="script.js"></script>
</head>
<body >
<div class="container-fluid">
<br />
<div class="row">
<div class="col-md-6">
<div class="panel-group">
<div class="panel panel-primary">
<div class="panel-heading">Example [As a Service]</div>
<div class="panel-body">
<div ng-controller='DummyController' class='col-md-6 c1'>
<form class="form-inline" role="form">
DummyController
<div>
Current Factory Value :
<input type='text' ng-model='property.prop'>
<br> Current Service Value :
<input type='text' ng-model='property1.prop'>
</div>
</form>
</div>
<hr>
<div ng-controller='Dummy1Controller' class='col-md-6 c2'>
<form class="form-inline" role="form">
Dummy1Controller
<div>
Current Factory Value :
<input type='text' ng-model='property.prop'>
<br> Current Service Value :
<input type='text' ng-model='property1.prop'>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Check out AngularJS Bootstraping guidelines here
https://docs.angularjs.org/guide/bootstrap
When doing this:
setTimeout(function(){
angular.bootstrap(document.querySelector(".c1"), ["myApp"])//manual bootstrapping of PaginationComp
angular.bootstrap(document.querySelector(".c2"), ["myApp"])
}, 1000);
You have more than one AngularJS application instance on your page and that is why the data is not shared between your controllers, since this service instances are living in different apps.
All you have to do is just to bootstrap the app once using the element that contains your ngController directives, for example:
setTimeout(function(){
angular.bootstrap(document.querySelector(".panel-body"), ["myApp"])
}, 1000);
Working fiddle:
(function() {
'use strict';
var app = angular.module('myApp', []);
app.factory('MyFactory', function() {
var myFactory = {};
myFactory.myProperty = {prop: 'Hello'};
myFactory.setProperty = function(value) {
this.myProperty.prop = value;
};
return myFactory;
});
app.service('MyService', function() {
this.myProperty = {prop: 'Test'};
this.setProperty = function(value) {
this.myProperty.prop = value;
}
});
app.controller('DummyController', DummyController);
DummyController.$Inject = ['$scope', 'MyFactory', 'MyService'];
app.controller('Dummy1Controller', Dummy1Controller);
Dummy1Controller.$Inject = ['$scope', 'MyFactory', 'MyService'];
function DummyController($scope, MyFactory, MyService) {
$scope.property = MyFactory.myProperty;
$scope.property1 = MyService.myProperty;
}
function Dummy1Controller($scope, MyFactory, MyService) {
MyFactory.setProperty('World1144');
$scope.property = MyFactory.myProperty;
MyService.setProperty('World1144');
$scope.property1 = MyService.myProperty;
}
})();
setTimeout(function(){
angular.bootstrap(document.querySelector(".panel-body"), ["myApp"])
}, 1000);
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body >
<div class="container-fluid">
<br />
<div class="row">
<div class="col-md-6">
<div class="panel-group">
<div class="panel panel-primary">
<div class="panel-heading">Example [As a Service]</div>
<div class="panel-body">
<div ng-controller='DummyController' class='col-md-6 c1'>
<form class="form-inline" role="form">
DummyController
<div>
Current Factory Value :
<input type='text' ng-model='property.prop'>
<br> Current Service Value :
<input type='text' ng-model='property1.prop'>
</div>
</form>
</div>
<hr>
<div ng-controller='Dummy1Controller' class='col-md-6 c2'>
<form class="form-inline" role="form">
Dummy1Controller
<div>
Current Factory Value :
<input type='text' ng-model='property.prop'>
<br> Current Service Value :
<input type='text' ng-model='property1.prop'>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Get autocompleted value from input in controller

I have the following in my view:
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
I am using google maps api for places to autocomplete the input boxes, so if a user starts typing "Lo", he will get a list of places that starts with "Lo" and for example he chooses London.
The problem is in my controller I am not getting the whole autocompleted value. I am only getting what the user initially entered, in this case "Lo".
Here is my controller:
app.controller('BookingsCtrl', function($scope, BookingsService) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
$scope.calcPrice = function() {
console.log($scope.pickup);
BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function(response) {
console.log(response.message);
});
};
});
EDIT:
Here is also a snippet of the JS:
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address;
var lat = place.geometry.location.lat();
var long = place.geometry.location.lng();
});
EDIT 2 : Added service
app.service('BookingsService', function ($resource) {
return $resource('http://localhost:3000/', {});
});
EDIT 3 : Template
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="assets/css/style.css" type="text/css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt1Y30OssBToIzSCOr3g5IkN3c0D75XVE&libraries=places"
></script>
</head>
<body ng-app='strelsau_client'>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<img class="masthead-brand" src="../assets/img/logo.png">
<nav>
<ul class="nav masthead-nav">
<li class="active">Home</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
<div ng-view>
</div>
</div>
</div>
</div>
<script src="components/jquery/dist/jquery.min.js"></script>
<script src="components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="components/angular/angular.min.js"></script>
<script src="components/angular-route/angular-route.min.js"></script>
<script src="components/angular-resource/angular-resource.min.js"></script>
<script src="js/main.js"></script>
<script src="js/controllers/bookings_controllers.js"></script>
<script src="js/services/bookings_service.js"></script>
</body>
</html>
In fact pickup input element is not getting updated once the place is resolved.
The problem with this function:
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address; //invalid
//...
});
For setting input field value should be used value property.
Anyway, given the example, try to replace it with:
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
Example
angular.module('myApp', [])
.controller('BookingsCtrl', function ($scope) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
$scope.calcPrice = function () {
console.log($scope.pickup);
alert($scope.pickup);
/*BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function (response) {
console.log(response.message);
});*/
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="myApp" ng-controller="BookingsCtrl" ng-cloak>
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
</div>

ng-repeat gets commented in the browser

I have a ng-repeat on a div which shows value from an array in the controller. The div is commented when I do the inspect element in the browser. I have an outer div with the ng-controller on it.
This is the html file:
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title></title>
<script type="text/javascript" src="../js/angular.js"></script>
<script type="text/javascript" src="../js/angular-route.js"></script>
<script type="text/javascript" src="../js/controller.js"></script>
<!-- <base href="localhost:5000/"/> -->
<base href="/"/>
</head>
<body>
<div ng-controller="firstController">
First name:<input type="text" ng-model="firstName"><br>
Last name:<input type="" ng-model="lastName"><br>
<input type="button" ng-click="loadView()" value="submit" name="">
<p>{{firstName}}</p>
<div ng-repeat="data in array">
{{data.name}}
</div>
</div>
</body>
</html>
This is the controller:
var app = angular.module('myapp',['ngRoute']);
// var app = angular.module('myapp',[]);
app.config(function($routeProvider,$locationProvider){
$routeProvider.when('/index',{
templateUrl:'./view/index.html',
controller:'firstController'
})
.when('/second/:firstName/:lastName',{
templateUrl:'./view/second.html',
controller:'secondController'
})
.otherwise({redirectTo:'/index'})
$locationProvider.html5Mode(true);
})
app.controller('firstController',function($scope,$location){
$scope.firstName = "";
$scope.lastName="";
$scope.loadView = function(){
$location.path('/second/'+$scope.firstName+"/"+$scope.lastName);
}
var arrays = [
{name:ab}, {name:ba}, {name:ac}, {name:ca}
];
$scope.array = arrays;
})
.controller('secondController',function($scope,$routeParams){
$scope.firstName = $routeParams.firstName;
$scope.lastName = $routeParams.lastName;
})
And also, when I try to navigate to second.html on button click which calls the loadView() in the controller, I see the url in the address bar has changed but it still shows the content of the first html(index.html).
The values for the array should be in single quotes unless they are variables. So instead of {name:ab} just do {name:'ab'}
Check out the snippet
var app = angular.module('myapp', []);
// var app = angular.module('myapp',[]);
app.controller('firstController', function($scope, $location) {
$scope.firstName = "";
$scope.lastName = "";
$scope.loadView = function() {
$location.path('/second/' + $scope.firstName + "/" + $scope.lastName);
}
var arrays = [{
name: 'ab'
}, {
name: 'ba'
}, {
name: 'ac'
}, {
name: 'ca'
}];
$scope.array = arrays;
})
.controller('secondController', function($scope, $routeParams) {
$scope.firstName = $routeParams.firstName;
$scope.lastName = $routeParams.lastName;
})
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="firstController">
First name:
<input type="text" ng-model="firstName">
<br>Last name:
<input type="" ng-model="lastName">
<br>
<input type="button" ng-click="loadView()" value="submit" name="">
<p>{{firstName}}</p>
<div ng-repeat="data in array">
{{data.name}}
</div>
</div>
</body>
</html>
The div gets commented when the object is empty.
Make sure that your $scope.object has the data that you want.

Clone Elements in Angular

I got this code from Vladyslav Babenko from this post over here (Clone elements in angularjs):
var App = angular.module('App', []).controller('Test', ['$scope',
function($scope) {
$scope.inputCounter = 0;
$scope.inputs = [{
id: 'input'
}];
$scope.add = function() {
$scope.inputTemplate = {
id: 'input-' + $scope.inputCounter,
name: ''
};
$scope.inputCounter += 1;
$scope.inputs.push($scope.inputTemplate);
};
$scope.teste = function (pergunta) {
console.log("in");
}
}
])
<!DOCTYPE html>
<html ng-app="App">
<head lang="en">
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="Test">
<form ng-submit="teste()">
<div class="pure-g entry" ng-repeat="input in inputs track by input['id']">
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="input" name="input-1">
</div>
<div class="pure-u-1-5">
<input type="text" class="pure-input-1" id="date" name="date">
</div>
<div class="pure-u-1-5">`enter code here`
<input type="text" class="pure-input-1" id="input-2" name="input-2">
</div>
</div>
</form>
<button type="button" id="add" ng-click="add()">Add</button>
<button type="submit">teste</button>
</body>
</html>
It works fine, but when a add multiples forms, how can I get the values from each form?
Give every input a ng-model:
<input type="text" class="pure-input-1" id="input-2" ng-model="user.name" name="input-2">
Now you can adress the input value in your controller with:
$scope.user.name
Read more about this topic: https://docs.angularjs.org/guide/forms

AngularJS: Sharing Data between 3 Controllers

I am using factory method in AngularJS to show the combination of First Name and Last Name (first two controllers) as Full Name(in third Controller), but i am not getting the desired output. here is my code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="Data.FirstName">
<br>FirstName is : <strong>{{Data.FirstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="Data.LastName">
<br>LastName is : <strong>{{Data.LastName}}</strong>
</div>
<div ng-controller="ThirdCtrl">
FullName is : {{Data.FirstName + " " + Data.LastName}}
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { FirstName: '',LastName:'' };
});
myApp.controller('FirstCtrl', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('ThirdCrl', function ($scope, Data) {
$scope.Data = Data;
});
</script>
</body>
</html>
Can you please Help?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="Data.FirstName">
<br>FirstName is : <strong>{{Data.FirstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="Data.LastName">
<br>LastName is : <strong>{{Data.LastName}}</strong>
</div>
<div ng-controller="ThirdCtrl">
FullName is : {{Data.FirstName + " " + Data.LastName}}
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { FirstName: '',LastName:'' };
});
myApp.controller('FirstCtrl', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('SecondCtrl', function ($scope, Data) {
$scope.Data = Data;
});
myApp.controller('ThirdCtrl', function ($scope, Data) {
$scope.Data = Data;
});
</script>
</body>
</html>
It seems you have spelled wrongly the third controller name.

Resources