First think i am new at angular. I am trying to call 1 function from 1 controller to another.
- With
ng-click=mapUsers1()
event its giving 2 alert but - without
ng-click=mapUsers1()
it giving only 1 pop
Is this feature of angular or i am doing something wrong......?
1.This is with $emit
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl2', function($scope, $rootScope) {
$rootScope.$on("call_mapUsers_Method", function() {
$scope.mapUsers();
})
$scope.mapUsers = function() {
alert("done....");
}
});
app.controller('myCtrl1', function($scope, $rootScope) {
$scope.mapUsers1 = function() {
alert('test');
$rootScope.$emit("call_mapUsers_Method", {});
}
$scope.mapUsers1();
});
</script>
<div ng-controller="myCtrl1">
<button ng-click="mapUsers1()">click</button>
<div ng-controller="myCtrl2"></div>
</div>
</body>
</html>
1.This is with $broadcast
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl2', function($scope, $rootScope) {
$rootScope.$on("call_mapUsers_Method", function() {
$scope.mapUsers();
})
$scope.mapUsers = function() {
alert("done....");
}
});
app.controller('myCtrl1', function($scope, $rootScope) {
$scope.mapUsers1 = function() {
alert('test');
$rootScope.$broadcast("call_mapUsers_Method", {});
}
$scope.mapUsers1();
});
</script>
<div ng-controller="myCtrl1">
<button ng-click="mapUsers1()">click</button>
<div ng-controller="myCtrl2"></div>
</div>
</body>
</html>
Edit: I have added example with $emit And $broadcast. with loading it will give only 1 alert but with button click it will give 2 alert ,that is seem odd