I want to know that can we communicate between two different controllers in AngularJS. Suppose I have Two modules,
Plunker: http://plnkr.co/edit/if0MQwlx9WHrD8XnMi2t?p=preview
1. var app = angular.module('fistModule', []);
app.controller('first', function ($scope) {
$scope.firstMethod= function () {
//my code}
} )
2. var newapp = angular.module('secondModule,[]');
newapp.controller('second', function ($scope) {
$scope.secondMethod= function () {
//my code}
Is there way to communicate between controllers of two different modules.
My Code:
JS:
angular.module('myApp', [])
.controller('ParentCtrl', ['$scope',
function($scope) {
$scope.message = "Child updated from parent controller";
$scope.clickFunction = function() {
$scope.$broadcast('update_parent_controller', $scope.message);
};
}
]);
angular.module('myNewApp', [])
.controller('ChildCtrl', ['$scope',
function($scope) {
$scope.message = "Some text in child controller";
$scope.$on("update_parent_controller", function(event, message) {
$scope.message = message;
});
}
])
HTML:
<div ng-app="myApp" ng-controller="ParentCtrl">
<div ng-app="myNewApp" ng-controller="ChildCtrl">
<p>{{message}}</p>
</div>
<button ng-click="clickFunction()">Click</button>
</div>
As #JB Nizet says, you do it the exact same way. You use a service to communicate between two controllers.
One module needs to have the other module as a dependency. This is always a one-way dependency. I have made secondModule a dependency of firstModule.
As well, the value in the service is stored in an object called data. This is because JavaScript does not pass values by reference -- but does pass objects by reference. So this is a form of boxing.
angular.module('firstModule', ['secondModule'])
.controller('FirstController', FirstController)
.service('sharedData', SharedData);
FirstController.$inject = ['sharedData'];
function FirstController(sharedData) {
this.data = sharedData.data;
}
function SharedData() {
this.data = {
value: 'default value'
}
}
angular.module('secondModule', [])
.controller('SecondController', SecondController);
SecondController.$inject = ['sharedData'];
function SecondController(sharedData) {
this.data = sharedData.data;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="firstModule">
<div ng-controller="FirstController as vm">
First Controller in module firstModule<br>
<input type=text ng-model="vm.data.value" />
</div>
<div ng-controller="SecondController as vm">
Second Controller in module secondModule<br>
{{vm.data.value}}
</div>
</div>
your plunker has a very minor issue.
change this
angular.module('myApp', [])
to
angular.module('myApp', ['myNewApp'])
Related
I found in Controller, we use $scope, here is the link (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_controller).
I change $scope to this, it cannot work.
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
However, I found in Service, we use this, here is the link (http://www.w3schools.com/angular/tryit.asp?filename=try_ng_services_custom).
In hexafy service, I change this to $scope, it cannot work.
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>
Does my above summary correct? If not, what should be correct summary considering all kinds of possible.
You can use this instead of $scope in controller as well. They have brought in controller as syntax(from Angular 1.2). You can attach data to this(Here controller holds the data). But internally it will be attached to $scope only, but you don't have to attach it manually. It has to be declared in html like this , controller is declared as main , so we have to refer to data in html using main.
<div ng-controller="MainCtrl as main">
{{ main.title }}
</div>
app.controller('MainCtrl', function ($scope) {
this.title = 'Some title';
console.log("Title" + $scope.main.title); // It will print some title in the console.
});
i am new to AngularJS so please forgive me this dump question.
i have error
Cannot set property 'test' of undefined
angularjs
var App = angular.module('StartModule', []);
App.controller('ModalDemoCtrl', [
function($scope) {
$scope.test = function() {
alert("12312");
}
}
]);
html
<body ng-app="StartModule">
<div ng-controller="ModalDemoCtrl">
<div ng-click="test()">11111</div>
</div>
<body>
You just miss $scope to controller's second argument:
var App = angular.module('StartModule', []);
App.controller('ModalDemoCtrl', [ $scope, function($scope) {
$scope.test = function() {
alert("12312");
}
}]);
You're missing the $scope dependency, you need to inject it in your controller :
App.controller('ModalDemoCtrl', ['$scope'
function($scope) {
That's why the $scope variable is undefined, you're not actually injecting any dependency in it.
This uses the Inline Array Annotation: https://docs.angularjs.org/guide/di
I'm starting using Angular JS to build a mobile application with Ionic.
I'm trying a thing very simple but it does not work.
HTML
<div ng-controller="MyCtrl">
Hello, {{name}}!
</div>
<div ng-controller="MyCtrl2">
Hello, {{name}}!
</div>
<button ng-controller="MyCtrl" ng-click="MyCtrl.test()">click</button>
JS
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Name 1';
$scope.test = function () {
$scope.name = 'Name on click !';
}
}
function MyCtrl2($scope) {
$scope.name = 'Name 2';
}
I have a similar structure in my Ionic App.
I need to modify the "$scope.name" from another template.
Thanks for help.
JSFiddle : http://jsfiddle.net/ADukg/6649/
This Fiddle will provide you with a working copy of your code.
<div ng-controller="MyCtrl">
<div>
Hello, {{name}}!
</div>
<div ng-controller="MyCtrl2">
Hello, {{name}}!
</div>
<button ng-click="test()">click</button>
</div>
(function() {
function MyCtrl($scope) {
$scope.name = 'Name 1';
$scope.test = function() {
$scope.name = 'Name on click !';
};
}
function MyCtrl2($scope) {
$scope.name = 'Name 2';
}
angular.module('myApp', [])
.controller('MyCtrl', MyCtrl)
.controller('MyCtrl2', MyCtrl2);
})();
You missed the following:
Assigning your controllers to your module
Wrapping the required template html in your ng-controller instead of
declaring it twice.
To modify scope from another controller you need to use either
$rootScope or angular js sevice .
Here is the $rootScope example:
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
I created an injectable value used in the entire application. Recently, I want to change it value. Here is the simulation of my situation:
angular.module('app', ['ngRoute']) // Create a value
.value('myValue','foo');
angular.module('app')
.controller('firstCtrl', ['$scope', '$filter', 'myValue', function($scope, $filter, myValue){
myValue = 'bar';
console.log(myValue); // bar
}])
.controller('secondCtrl', ['myValue', function(myValue){
console.log(myValue); // foo
}]);
However, the value of myValue didn't change at all, as you can see in the secondCtrl. How can I change this value? Any suggestion would be appreciated.
Google 'angular dot rule', and you've got twice defined app module.
Please see demo below.
var app = angular.module('app', []);
angular.module('app') // Create a value
.value('myValue', {
data: 0
});
app.controller('homeCtrl', function($scope, myValue) {
$scope.value = myValue;
$scope.update = function() {
myValue.data = 8;
}
});
app.controller('secondCtrl', function($scope, myValue) {
$scope.value = myValue;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="app">
<div ng-controller="homeCtrl">
<button ng-click="update()">update</button>
<br/>home: {{value.data}}
</div>
<hr/>
<div ng-controller="secondCtrl">
second: {{value.data}}
</div>
</div>
</body>
I have a controller as main controller and a its child controller. I want to execute first the main controller and then after its child controller.
I am collecting some userdata and want to keep it in $rootScope so that i could access it within the whole application.
How could i do this ?
<body ng-app="angularApp">
<div ng-controller="MainAppController">
<div ng-controller="childController">
Here i want to access data from "MainAppController" stored in $rootScope
But problem is "childController" runs before "MainAppController"
</div>
</div>
</body>
Here is the angular code
angular.module('MyApp').controller('MainAppController', function($rootScope, service){
$rootScope.userData = [];
service.getUserData().success(function(userDetails){
$rootScope.userData = userDetails;
});
});
angular.module('MyApp').controller('childController', function($scope, $rootScope){
$scope.userInfo = $rootScope.userData;
//Here $scope.userInfo is null because $rootScope.userData gets assigned to $scope.userInfo in this controller before userDetails gets assigned to $rootScope.userData in MainAppController controller.
I want that untill "$rootScope.userData = userDetails;" is not finished , "$scope.userInfo = $rootScope.userData;" must not run.
How can i do this ?
});
There are two ways i know you can do this.
1 way ::
Use $rootScope.userData directly in html and when your parent controller will run $rootScope.userData will get updated and by dual binding feature of angular, your view will get updated accordingly
Code::
//angularjs Code
var app = angular.module('MyApp', []);
app.controller('MainController', function($rootScope, $timeout) {
$rootScope.userData = {};
$timeout(function() {
$rootScope.userData = {name:'myName'};
}, 3000);
});
app.controller('childController', function() {
});
//html code
<div ng-app="MyApp" ng-controller="MainController">
<div ng-controller="childController">
{{userData.name}}
</div>
</div>
2 way::
You can attach $watch on $rootScope.userData in childController so when $rootScope.userData will get updated $watch will run and inside $watch you can update your $scope variable
Code::
//Angularjs Code
var app = angular.module('MyApp', []);
app.controller('MainController', function($rootScope, $timeout) {
$rootScope.userData = {};
$timeout(function() {
$rootScope.userData = {name:'myName'};
}, 2000);
});
app.controller('childController', function($scope, $rootScope) {
$scope.$watch(function(){
return $rootScope.userData;
}, function(){
$scope.userInfo = $rootScope.userData;
});
});
//HTML Code
<div ng-app="MyApp" ng-controller="MainController">
<div ng-controller="childController">
{{userInfo.name}}
</div>
</div>