I am new to Angular js.I have seen the similar question, but I dont understand that.
I have 2 controllers
userControllers.controller('RatingCtrl', function($scope,$http,$rootScope,$route)
userControllers.controller('otherProfileCtrl', function ($scope, $routeParams, $rootScope, $http, $location, $window, $timeout,$uibModal, $compile)
RatingCtrl and otherProfileCtrl, this two modules are inter-related. My need is that, I have reload RatingCtrl from otherProfileCtrl using $route.reload();.Is there is any way to do this without uisng service?plz help
You could pass events from one controller to another in order to achieve this. You would then do something like:
var app = angular.module('myApp', []);
app.controller('firstController', ['$scope', '$rootScope',
function($scope, $rootScope) {
$scope.text = 'Initial text';
$scope.changeText = function(message) {
$scope.text = message;
};
$rootScope.$on('customEvent', function(event, message) {
$scope.changeText(message);
});
}
]);
app.controller('secondController', ['$scope',
function($scope) {
$scope.message = 'Message from second controller';
$scope.sendEvent = function() {
$scope.$emit('customEvent', $scope.message)
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="firstController">
<h2>This is the fist controller:</h2>
<p>{{text}}</p>
</div>
<div ng-controller="secondController">
<h2>This is the second controller:</h2>
<input type="text" ng-model="message" />
<br>
<button ng-click="sendEvent()">Send message</button>
</div>
</div>
Here, the firstController listens to events propagated to the $rootScope, and the secondController sends the message. That is the functionality that you are looking for.
That being said, you would be much better off implementing shared behaviour in a service, since keeping track of all your custom events can be particularly tough.
Hope this helps.
Related
I am trying to get FirstCtrl data in SecondCtrl, but there is no response in SecondCtrl, Please help me to solve this
I Have tried to use $broadcast and $emit on $rootscope. but there is not data coming on $on
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function( $scope, $rootScope) {
$scope.firstName = 'Ganpat';
//$rootScope.$emit('firstName', $scope.firstName);
$rootScope.$broadcast('firstName:broadcast', $scope.firstName);
});
myApp.controller('SecondCtrl', function( $scope, $rootScope){
$rootScope.$on('firstName:broadcast', function(event,data){
$scope.firstName = data;
console.log(data);
});
});
</script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstName}}
</div>
</div>
</body>
</html>
Code now compiles and runs properly. You can cut and past this into fiddler and run.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('UserService', function () {
var self = this;
var firstName = '';
self.SetFirstName = function (name) { firstName = name; }
self.GetFirstName = function () { return firstName; }
return self;
});
myApp.controller('FirstCtrl', ['$scope', 'UserService', function ($scope, UserService) {
UserService.SetFirstName("coolMan");
}]);
myApp.controller('SecondCtrl', ['$scope', 'UserService', function ($scope, UserService) {
$scope.firstNameTest = '';
$scope.service = UserService;
$scope.$watch('service.GetFirstName()', function (newVal) {
console.log("New Data", newVal)
$scope.firstNameTest = newVal;
});
}]);
</script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>
Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstNameTest}}
</div>
</div>
</body>
</html>
EDIT
Addressing OPS comment.
I know this method will work and it will give a correct result, but i
have studied the $rootscope and event $emiter and $broadcast will do
this trick, so if you know about that then please tell me, thank you
for your answer.
What you want to do is a bad idea. Your method forces a tighter coupling between controllers. By working on the rootscope you are forcing all controllers to rely on a certain Item being in rootscope. This is bad because controllers are not self contained modules.
By passing around a service you can decouple the controllers. Meaning that they can be used as view controllers, directive controllers, pretty much anything that requires an isolated module.
Also using a service you can now cache the result, perform centralized business logic on it, and encapsulate how you get the data. This cannot be done easily on the rootscope.
To sum it up, I will not show you a terrible way of doing what you want done. It is not good and will let other people whom look at this post use bad practices.
I am using angular 1.x and I am trying to share data from one controller to another
I am using the above model in mainctrl. The radiotmplt.radiohead=='IRU600v3'is from firstctrl. I cannot share data using rootscope. Please advise.
Here is the demo how to share data using RootScope
link Jsfiddle
Js
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $rootScope) {
$scope.data = 'data';
$rootScope.data1 = 'old data';
$scope.setVal = function() {
$rootScope.data1 = 'new data';
}
});
app.controller('ctrl2', function($scope, $rootScope) {
$scope.data = $rootScope.data1;
$scope.$watch('data1', function(o, n) {
$scope.data = $rootScope.data1;
})
});
HTML
<div ng-app='myApp'>
<div ng-controller='ctrl1'>
controller 1
<input type='text' ng-model='data'>
<button ng-click='setVal()'>
Change
</button>
</div>
<hr>
<div ng-controller='ctrl2'>
controller 2
<input type='text' ng-model='data'>
</div>
</div>
Hope this will help you
I am wondering at the dual behaviour of $scope. In the below script I am getting value of name as alert. But in my ionic app the same code alerts undefined.
I googled the problem and found this link as a solution where it states that we need to use dot(.) in order to get the value in ng-model. What is the difference between two.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a =function a(){alert($scope.name);}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name" ng-blur="a()">
</div>
Try changing your controller function as below:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a =function(){
alert($scope.name);
}
});
Actually it does work with Ionic,
angular.module('starter.controllers', [])
.controller('myCtrl', function($scope) {
$scope.a = function a() {
alert($scope.name);
}
})
DEMO
Solution :
"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.
Controller
$scope.formData = {};
$scope.check = function () {
console.log($scope.formData.searchText.$modelValue); //works
}
Template
<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>
This happens when child scopes are in play - like child routes or ng-repeats.
The child-scope creates it's own value and a name conflict is born as illustrated here:
See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s
.
And that is referred from below links :
Other Solutions
Use this keyword instead of $scope, More details
And also you can get more details from this below two discussions
Ng-model does not update controller value
Why is my ng-model variable undefined in controller?
Update Solution 1 :
Please declaring the blank object first at the top of your controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "";
$scope.a = function(){alert($scope.name);}
});
I hope these will be helps to you.
Try to use json object.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.user = {'name':''};
$scope.a =function a(){alert($scope.user.name);}
});
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="user.name" ng-blur="a()">
</div>
My code is something like this
HTML view
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="get_user_detail(Andrew)">
</button>
<button ng-click="get_user_detail(Andrew1)">
</button>
</div>
AngularJS
var app = angular.module("myApp", []);
app.controller("myCtrl", ['$compile', '$http', '$scope', function ($compile, $http, $scope) {
$scope.get_user_detail=function(name){
var response = $http.get("myURL", {
params: {user_id:12345,name:name}
});
response.success();
response.error();
}
}]);
While I was working with one parameter user_id,it was working fine,parameters were passed properly to request.After I added 2nd parameter name,it is not getting passed in params.
Andrew is not a variable of your $scope.
So when you do get_user_detail(Andrew), the value of Andrew is undefined.
I guess you would like to pass it as a static value (string), put your value between quotes ' ':
<button ng-click="get_user_detail('Andrew')">
As in the other answers, your code should work as long as you add " " to the strings you intend to pass as params.
var app = angular.module('ngApp', []);
app.controller("myCtrl", ['$compile', '$http', '$scope', function ($compile, $http, $scope) {
$scope.get_user_detail = function(name){
$scope.name = name
// response = $http.get("myURL", {
// params: {user_id:12345,name:name}
// });
// response.success();
// response.error();
}
}]);
<div ng-app="ngApp" ng-controller="myCtrl">
You clicked {{name}} <br/>
<button ng-click="get_user_detail('Andrew')"> Andrew
</button>
<button ng-click="get_user_detail('Bob')"> Bob
</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="app.js"></script>
</div>
I commented the $http call for obvious reasons. Hope it helps.
You must have string in ng-click in ' ':
<button ng-click="get_user_detail('Andrew')">
and in js code - name put in ' '
params: {user_id:12345,'name':name}
I thought you not define variables in controller, define variable with $scope
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="get_user_detail(Andrew)">
</button>
<button ng-click="get_user_detail(Andrew1)">
</button>
</div>
Controller Code
var app = angular.module("myApp", []);
app.controller("myCtrl", ['$compile', '$http', '$scope', function ($compile, $http, $scope) {
$scope.Andrew = 'John';
$scope.Andrew = 'Jam';
$scope.get_user_detail=function(name){
var response = $http.get("myURL", {
params: {user_id:12345,name:name}
});
response.success();
response.error();
}
}]);
Other soluation you can direct pass string without define variable
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="get_user_detail('Andrew')">
</button>
<button ng-click="get_user_detail('Andrew1')">
</button>
</div>
How to reduce the dependencies that we give in angular js controllers like
app.controller('sampleController', function($scope, $timeout, $localStorage, $http, $location))
.controller('sample1Controller', function($scope, $timeout, $localStorage, $http, $location))
.controller('sample2Controller', function($scope, $timeout, $localStorage, $http, $location))
.controller('sample3Controller', function($scope, $timeout, $localStorage, $http, $location))
and I'm using the same set of dependencies for multiple controllers.
Can we store all the dependencies in a variable use that to all the controllers.
try to create services for the functionality in the controllers. then your code will be like this, for example,
app.controller('sampleController', function($scope, serviceA, $location))
app.service('serviceA', function($timeout, $localStorage, $http) {
// do something here
});
the more you abstract code out of your controllers, less your injections will be
You can create custom service in angular which returns the dependencies and you can inject that service in your controller and access them. but you will not be able to include $scope in the service as scope is available only for controller.
// angular module implementation
(function(){
'use strict';
angular
.module('app',[]);
})();
// angular controller
(function(){
'use strict';
var controllerId = 'myCtrl';
angular
.module('app')
.controller(controllerId,['common',function(common){
var vm = this;
init();
function init(){
vm.count = 0;
common.interval(function(){
vm.count++;
}, 1000);
}
}]);
})();
// service that returns the depandancies
(function(){
'use strict';
var serviceId = 'common';
angular
.module('app')
.factory(serviceId, ['$timeout','$interval', function($timeout,$interval){
return {
timeout: $timeout,
interval: $interval
};
}]);
})();
<!DOCTYPE html>
<html>
<head>
<script data-require="angularjs#1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller='myCtrl as vm'>
<h1>My Count is: {{vm.count}}!</h1>
</body>
</html>
To eliminate $scope from your controller go ahead mvvm approach. http://www.johnpapa.net/angularjss-controller-as-and-the-vm-variable/
If you don't want to see all the dependencies statically injected to your controllers and need to do it in a single place, you can use $injector to create an object which will give reference to all your dependencies.
.factory('dependencies', function($injector){
var dependencies;
dependencies.fooDependency = $injector.get('fooDependency');
dependencies.barDependency = $injector.get('barDependency');
return dependencies;
})
Inject this factory to your controller and use it to access your dependencies.