I've below requirement.
I've three controllers, ctrl 1, ctrl 2 and ctrl 3. I want to pass the value firstName to ctrl 1, lastName to ctrl2 and get the full name from ctrl3 using button click event.
I've tried my below code but I'm getting output as NaN.
Please help.
<script>
var myApp = angular.module('myApp', []);
myApp.factory('data', function () {
var factory = {};
var firstName = '';
var secondName = '';
factory.getName = function () {
return firstName + ' ' + secondName;
}
return factory;
});
myApp.controller('FirstController', function ($scope, data) {
$scope.firstName = data.firstName
});
myApp.controller('SecondController', function ($scope, data) {
$scope.secondName = data.secondName;
});
myApp.controller('ThirdController', function ($scope, data) {
$scope.getFullName = function () {
$scope.fullName = data.getName();
}
});
</script>
<h2>Controller 1</h2><br />
<div ng-controller="FirstController">
<input type="text" ng-model="data.firstName">
<br>FirstName is : {{data.firstName}}
</div>
<hr>
<h2>Controller 2</h2><br />
<div ng-controller="SecondController">
<input type="text" ng-model="data.secondName">
<br>LastName is : {{data.secondName}}
</div>
<h2>Controller 3</h2><br />
<div ng-controller="ThirdController">
<button ng-click="getFullName()">Get full Name</button>
Full name is: {{fullName}}
</div>
</div>
Try this method.
HTML:
<div ng-controller="BaseController">
<p>Base Controller Value: {{model.getValue()}}</p>
<button ng-click="model.updateValue('Value updated from Base')">Update In Base</button>
<div ng-controller="DerivedController">
<p>Derived Controller Value: {{model.getValue()}}</p>
<button ng-click="model.updateValue('Value updated from Derived')">Update In Derived</button>
</div>
</div>
JavaScript:
app.factory('sharedModel', function () {
// private stuff
var model = {
value: "initial Value"
};
// public API
return {
getValue: function() {
return model.value;
},
updateValue: function(value) {
model.value = value;
}
};
});
function BaseController($scope, sharedModel) {
$scope.model = sharedModel;
}
function DerivedController($scope, sharedModel) {
$scope.model = sharedModel;
}
WorkingFiddle.
Hope it helps!
Issues in your code snippet:
The service does not know about firstName and secondName properties.
data is not a $scope object in first and second controller.
No object allocation for the property in the service. "Save" button to bind to service.
var myApp = angular.module('myApp', []);
myApp.service('data', function () {
var service = {};
service.firstName = '';
service.secondName = '';
service.getName = function () {
return this.firstName + ' ' + this.secondName;
}
return service;
});
myApp.controller('FirstController', function ($scope, data) {
$scope.saveToService = function() {
data.firstName = $scope.firstName;
}
});
myApp.controller('SecondController', function ($scope, data) {
$scope.saveToService = function() {
data.secondName =$scope.secondName;
}
});
myApp.controller('ThirdController', function ($scope, data) {
$scope.getFullName = function () {
$scope.fullName = data.getName();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<h2>Controller 1</h2><br />
<div ng-controller="FirstController">
<input type="text" ng-model="firstName">
<button ng-click="saveToService()">Save</button>
<br>FirstName is : {{firstName}}
</div>
<hr>
<h2>Controller 2</h2><br />
<div ng-controller="SecondController">
<input type="text" ng-model="secondName">
<button ng-click="saveToService()">Save</button>
<br>LastName is : {{secondName}}
</div>
<h2>Controller 3</h2><br />
<div ng-controller="ThirdController">
<button ng-click="getFullName()">Get full Name</button>
Full name is: {{fullName}}
</div>
</body>
Related
I'm trying to get md-autocomplete to play nice with Algolia's Angular service. I'm stuck on getting the dropdown to display the results being returned from Algolia. The content is in console yet the dropdown will not populate with the updated results. What am I missing?
tl;dr: Plnkr
"Backend"
.controller('DemoCtrl', DemoCtrl);
function DemoCtrl ($timeout, $q, $log, algolia, $http, $scope) {
var self = this;
self.simulateQuery = false;
self.isDisabled = false;
self.repos = loadAll();
self.querySearch = querySearch;
self.selectedItemChange = selectedItemChange;
self.searchTextChange = searchTextChange;
// Algolia demo keys below
var client = algolia.Client('latency', '6be0576ff61c053d5f9a3225e2a90f76');
var index = client.initIndex('contacts');
$scope.query = '';
$scope.hits = [];
// Disable cache
$scope.noCacheResults = false;
// ******************************
// Internal methods
// ******************************
/**
* Search for repos... use $timeout to simulate
* remote dataservice call.
*/
function querySearch (query) {
// This returns objects in console
var results = self.algoliaSearch(query);
// This returns: TypeError: Cannot read property 'then' of undefined
// var results = query ? self.algoliaSearch( createFilterFor(query) ) : self.repos, deferred;
return results;
}
function searchTextChange(text) {
$log.info('Text changed to ' + text);
}
function selectedItemChange(item) {
$log.info('Item changed to ' + JSON.stringify(item));
}
/**
* Build `components` list of key/value pairs
*/
function algoliaSearch(text) {
try {
index
.search(text)
.then(function(content) {
// if (content.query !== $scope.query) {
// // do not take out-dated answers into account
// return;
// }
$scope.hits = content.hits;
return content.hits.map( function (hit) {
hit.value = hit.name.toLowerCase();
$log.debug(hit);
return hit;
});
}, function(content) {
console.log('Error: ' + content.message);
});
} catch(e) {
$log.debug(e);
}
}
function loadAll() {
var repos = [
{
'name' : 'Angular 1',
'url' : 'https://github.com/angular/angular.js',
'watchers' : '3,623',
'forks' : '16,175',
}
];
return repos.map( function (repo) {
repo.value = repo.name.toLowerCase();
return repo;
});
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(item) {
return (item.value.indexOf(lowercaseQuery) === 0);
};
}
}
"Frontend"
<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak>
<md-content layout-padding layout="column">
<form ng-submit="$event.preventDefault()">
<p>Use <code><md-autocomplete></code> with custom templates to show styled autocomplete results.</p>
<md-autocomplete
ng-disabled="ctrl.isDisabled"
md-no-cache="ctrl.noCacheResults"
md-selected-item="ctrl.selectedItem"
md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
md-search-text="ctrl.searchText"
md-selected-item-change="ctrl.selectedItemChange(item)"
md-items="item in ctrl.querySearch(ctrl.searchText)"
md-item-text="item.name"
md-min-length="0"
placeholder="Pick an Angular repository"
md-menu-class="autocomplete-custom-template">
<md-item-template>
{{item}}
<span class="item-title">
<md-icon md-svg-icon="img/icons/octicon-repo.svg"></md-icon>
<span> {{item.name}} </span>
</span>
<span class="item-metadata">
<span class="item-metastat">
<strong>{{item.watchers}}</strong> watchers
</span>
<span class="item-metastat">
<strong>{{item.forks}}</strong> forks
</span>
</span>
</md-item-template>
</md-autocomplete>
</form>
</md-content>
</div>
"Algolia default"
<section class="panel">
<header class="panel-heading">
<div class="search_box">
<form action="#" method="get">
<input autocomplete="off" class="autocomplete" placeholder="Start typing" type="text" spellcheck="false" id="q" ng-model="query" />
<div class="searchbutton">
<i class="icon-search icon-large"></i>
</div>
</form>
</div>
</header>
</section>
<h1>Results</h1>
<div class="hit" ng-repeat="hit in hits">
<div class="attribute" ng-repeat="(attribute,v) in hit._highlightResult">
<span>{{ attribute }}: </span>
<span ng-bind-html="v.value"></span>
</div>
</div>
<script type="text/javascript">
angular
.module('myapp', ['algoliasearch', 'ngSanitize'])
.controller('SearchCtrl', ['$scope', 'algolia', function($scope, algolia) {
$scope.query = '';
$scope.hits = [];
// Replace the following values by your ApplicationID and ApiKey.
var client = algolia.Client('latency', '6be0576ff61c053d5f9a3225e2a90f76');
// Replace the following value by the name of the index you want to query.
var index = client.initIndex('contacts');
$scope.$watch('query', function() {
index.search($scope.query, { hitsPerPage: 5 }).then(function(content) {
if (content.query !== $scope.query) {
// do not take out-dated answers into account
return;
}
$scope.hits = content.hits;
}, function(content) {
console.log('Error: ' + content.message);
});
});
}]);
</script>
You should return a Promise since the call to AlgoliaSearch is asynchronous:
function querySearch(query) {
return algoliaSearch(query);
// var results = query ? self.algoliaSearch( createFilterFor(query) ) : self.repos, deferred;
}
You can find the updated code here: http://plnkr.co/edit/C8fmsNRzNsXEC7InNM6a
I want to share data with two controllers, but my application has one bug. When I click x2 for the first time, it returns NAN, but on second time it works correctly.
I'm trying to solve this question.
var mainApp = angular.module("mainApp", []);
mainApp.service('MathService', function() {
this.multiply = function(a, b) {
return a * b
}
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a, a);
}
});
mainApp.service('Data', function() {
return {
result: ''
};
});
mainApp.controller('CalcController', function($scope, CalcService, Data) {
$scope.square = function() {
$scope.Data = Data;
$scope.result = CalcService.square(Data.number);
}
});
mainApp.controller('CalcController2', function($scope, MathService, Data) {
$scope.multiply = function() {
$scope.Data = Data;
$scope.result2 = MathService.multiply(Data.number, $scope.number2);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp">
<div ng-controller="CalcController2">
<p>
Enter a number:
<input type="number" ng-model="number2">
<button ng-click="multiply()">multiply</button>
<p>Result x*y: {{result2}}</p>
<div ng-controller="CalcController">
<button ng-click="square()">X<sup>2</sup></button>
<p>Result x2:{{result}}</p>
<br>
<p>
Enter a number:
<input type="number" ng-model="Data.number">
</div>
</div>
</div>
</body>
The code is working fine. The reason is you are leaving the second input blank and hence the whole multiplication breaks.
Please checkout this.
var mainApp = angular.module("mainApp", []);
mainApp.service('MathService', function() {
this.multiply = function(a, b) {
return a * b
}
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a, a);
}
});
mainApp.service('Data', function() {
return {
result: ''
};
});
mainApp.controller('CalcController', function($scope, CalcService, Data) {
$scope.square = function() {
debugger;
Data=$scope.Data;
$scope.Data = Data;
$scope.result = CalcService.square(Data.number);
}
});
mainApp.controller('CalcController2', function($scope, MathService, Data) {
$scope.Data = {number:1};
$scope.multiply = function() {
debugger;
Data=$scope.Data;
$scope.Data = Data;
$scope.result2 = MathService.multiply(Data.number, $scope.number2);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp">
<div ng-controller="CalcController2">
<p>Enter a number:
<input type="number" ng-model="number2">
<button ng-click="multiply()">multiply</button>
<p>Result x*y: {{result2}}</p>
<div ng-controller="CalcController">
<button ng-click="square()">X<sup>2</sup>
</button>
<p>Result x2:{{result}}</p>
<br>
<p>Enter a number:
<input type="number" value="0" ng-model="Data.number">
</div>
</div>
</div>
</body>
I want a angularjs code in which 1 controller is using .service set method to set the value and another controller using the .service get method to retrieve that value.
also i tried this code please let me know why it is not printing the right output.
i tried this code but after setting value it is not printing value...can you help me out in this ..
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" ></script>
<script>
var app = angular.module('myApp', []);
app.service('sharedProperties', function() {
var stringValue = ' ';
return{
getString: function() {
return stringValue;
},
setString: function(value) {
stringValue = value;
}
}});
app.controller('get', function($scope,sharedProperties) {
$scope.stringValue = sharedProperties.getString();
});
app.controller('set', function($scope, sharedProperties) {
$scope.setString = function(newValue) {
$scope.objectValue.data = newValue;
sharedProperties.setString(newValue);
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="set">
<input type=text ng-model="newValue">
<button onclick="setString(newValue)" >Click here</button>
</div>
<div ng-controller="get">
value is {{stringValue}}
</div>
</body>
</html>
Answers will be appreciated.
I dont understand what is stopping you?
Just read the angular docs https://docs.angularjs.org/guide/services
Quick fiddle
angular.module('serviceApp',[]);
angular.module('serviceApp').service('SharedService',[function(){
var value = '';
this.set = function(val){
value = val;
};
this.get = function(val){
return value;
}
}]);
angular.module('serviceApp').controller('OneCtrl',['$scope','SharedService',function($scope,sharedService){
$scope.form = {value:''}
$scope.setValue = function(){
sharedService.set($scope.form.value);
}
}]);
angular.module('serviceApp').controller('TwoCtrl',['$scope','SharedService',function($scope,sharedService){
$scope.value = sharedService.get();
$scope.getValue = function(){
$scope.value = sharedService.get();
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="serviceApp">
<div ng-controller="OneCtrl">
<input ng-model="form.value" type="text" />
<button type="button" ng-click="setValue()">Set</button>
</div>
<div ng-controller="TwoCtrl">
<button type="button" ng-click="getValue()">Get</button>
Value: {{value}}
</div>
</div>
My view is:
<div class="container" ng-controller="MyController">
<div class="row">
<div class="col-md-8">
<textarea class="form-control" rows="10" ng-model="myWords" ng-change="parseLanguage()"></textarea>
</div>
<div class="col-md-4" ng-show="sourceLanguage !== null">
Language: {{ sourceLanguage }}
</div>
</div>
</div>
My controller is:
webApp.controller('MyController', [
'$scope', '$rootScope', 'TranslateService', function($scope, $rootScope, CodeService) {
$scope.init = function() {
return $scope.sourceLanguage = null;
};
$scope.parseLanguage = function() {
return TranslateService.detectLanguage($scope.myWords).then(function(response) {
console.log($scope.sourceLanguage);
$scope.sourceLanguage = response.data.sourceLanguage;
return console.log($scope.sourceLanguage);
});
};
return $scope.init();
}
]);
The console logs show the right data. But in the view, sourceLanguage never updates. Why would this be?
In case the promise you are evaluating is not part of the Angular context you need to use $scope.$apply:
$scope.parseLanguage = function() {
TranslateService.detectLanguage($scope.myWords).then(function(response) {
$scope.$apply(function() {
$scope.sourceLanguage = response.data.sourceLanguage;
});
});
};
This is my first application in Angular. I was not sure why it is not working.
<body ng-controller="LoginController">
<div name="signIn" class="box-content">
<div class="box-top-content">
<label>Username:</label><input type="text" ng-model="username" /></br>
</br> <label></label>Password:</label><input type="password" ng-model="password"></br>
<button type="submit" ng-click="submit()">login</button>
</div>
My JS is:
var loginApp = angular.module('loginApp', []);
loginApp.factory('authFactory',function(){
var authFactory ={};
authFactory.login = function (username,password){
if ( username == "abc" && password=="test")
return true;
else
return false;
};
return authFactory;
});
loginApp.controller('LoginController', function($scope,authFactory) {
$scope.submit= function ($scope,authFactory) {
authFactory.login($scope.username, $scope.password).then(function (status) {
if (status) {
alert("not welcome");
}
else {
alert("welcome");
}
});
};
});
When I click on Submit button ,nothing happens. No error message. Whats wrong with this code?
You need to return the object inside of the factory:
loginApp.factory('authFactory',function($http){
var authFactory ={};
authFactory.login = //...
return authFactory; //Here it is
});