Hi I am developing angular js application. I am using ui-routing technique. I am facing issues in button click event. Below is my main.js file.
var app = angular.module('RoslpApp', ['pascalprecht.translate', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider) {
$stateProvider.state('ForgotPassword', {
url: '/ForgotPassword',
templateUrl: 'ForgotPassword/ForgotPassword.html',
controller: 'ForgotPassword'
});
$stateProvider
.state('ForgotPassword.ResetPassword', {
url: '/ResetPassword',
templateUrl: 'ForgotPassword/ResetPassword.html',
controller: 'ResetPassword'
});
});
});
Below is my forgotpassword.html
<div class="container">
<div ui-view></div>
</div>
Here i am injecting ResetPassword.html.
Below is my ResetPassword.html
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
Above button does not work.
This is my Resetpasswordcontroller.
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$rootScope', '$translatePartialLoader', '$translate', function ($ResetPasswordService, $scope, $translatePartialLoader, $translate) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
})();
Resetpasswordservice.js
app.service("ResetPasswordService", function ($http, $state) {
alert("aaa");
this.ResetPassword = function () {
var url = '/api/projects/7';
return $http.post(url).then(function (response) {
return response.data;
});
}
});
$scope.ResetPassword is not working and i am not getting error also. Any help would be appreciated. Thank you.
I think your arguments are wrong, try to change it to something like this (corresponding arguments):
[
'$rootScope',
'ResetPasswordService',
'$scope',
'$translatePartialLoader',
'$translate',
function ($rootScope, $ResetPasswordService, $scope, $translatePartialLoader, $translate){
[...]
}
]
Your dependency injection order is wrong. Try this one:
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$scope', '$http', '$translatePartialLoader', '$translate', 'ResetPasswordService', function ($scope, $http, $translatePartialLoader, $translate, ResetPasswordService) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
$http.post('/api/projects/7').then(function (response) {
alert(JSON.stringify(response.data));
}, function (error) {
console.log(error);
});
}
}]);
})();
ResetPasswordService.js
angular.module('RoslpApp').service("ResetPasswordService", function ($http, $state) {
alert("aaa");
this.ResetPassword = function () {
var url = '/api/projects/7';
return $http.post(url).then(function (response) {
return response.data;
});
}
});
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$rootScope' , function( $scope){
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$rootScope' , function( $scope){
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
<!-- begin snippet: js hide: false console: true babel: false -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
There may be problme while passing the dependency to controller in passing the arguments to callback.I tried simple way with one arguments.its work to me.Check it
Change your code like below. Your order and reference is wrong.
angular.module('RoslpApp').controller('ResetPassword', ['$rootScope','$scope', '$translatePartialLoader', '$translate','ResetPasswordService', function ($rootScope, $scope, $translatePartialLoader, $translate,ResetPasswordService) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
Change you ResetPassword.html code as following:
<div class="button-container">
<input type="button" value="Submit" id="input-submit" ng-click="ResetPassword()" />
</div>
Also, edit you controller as the problem is due to incorrect dependencies order. You should rewrite as:
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$ResetPasswordService','$scope', '$translatePartialLoader', '$translate', function ($ResetPasswordService, $scope, $translatePartialLoader, $translate) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
})();
Related
below is my first controller
.controller('configManagementCtrl', ['$scope', 'deConfigService', 'ngDialog', '$state', 'notificationService',
function ($scope, deConfigService, ngDialog, $state, notificationService) {
$scope.loadDetails = function () {
....
};
$scope.openModal = function () {
var newClassDialog = ngDialog.open({
template: 'views/modals/newClassModal.html',
closeByEscape: false,
controller: 'newClassController',
className: 'ngdialog-theme-default',
width: 600
});
newClassDialog.closePromise.then(function (data) {
console.log(data);
if (data.passBackData.value === 2) {
$scope.loadDetails();
// $state.go('app.config', {}, {reload: true, inherit: false});
// $scope.loadDetails();
}
});
};
}])
In my second controller am trying to send some data to my parent controller as shown below
.controller('newClassController', ['$scope', 'ngDialog', 'deConfigService', 'notificationService',
function ($scope, ngDialog, deConfigService, notificationService) {
$scope.classObj = {};
var passBackData = [];
$scope.cancel = function () {
passBackData.push({'closeVal': 1});
console.log(passBackData);
ngDialog.close(1, passBackData);
};
$scope.create = function (isFormValid) {
if (isFormValid) {
$scope.classObj.added_dt = (new Date()).toISOString();
$scope.classObj.class_id = 0;
deConfigService.createClass($scope.classObj, function (response) {
if (response.data) {
console.log(response.data);
passBackData.push(response.data.data);
notificationService.addSuccess('Class created successfully');
}
else {
notificationService.addError('Error!! Please try later');
}
});
ngDialog.close(1, 2);
}
};
}])
below is the ngdialog html. It has 2 textbox which am able to get data to my second controller but not able to send response back to first controller
<form ng-submit="create(form.$valid)" name="form" novalidate="">
<div class="form-flex ng-pristine ng-invalid ng-touched">
<div class="form-tile">
<label>Class name </label>
<input type="text" ng-model="classObj.name" name="form.name" placeholder="Enter the name of your class" required>
<label>Class description</label>
<textarea ng-model="classObj.description" name="form.description" placeholder="Enter a short description" rows="5" required></textarea>
</div>
</div>
<button type="submit" ng-click="submittedForm = true;" ng-disabled="form.$invalid" class="mat-raised-button-blue"> Create </button>
<button class="mat-raised-button" style="float:right; width:155px" ng-click="cancel();"> Cancel </button>
</form>
Am pushing some objects to the array and trying to send but not able to receive it from parent controller.
Where am doing wrong?
After a closer read of the documentation, it looks like you need to call .close() passing the id of the dialog and the value to return from the dialog's controller. In your parent controller the object passed back to your closePromise callback has id and value properties. You'll need to get whatever you're passing back via the value property (i.e. data.value.whateverYouAreReturning). Here is a simple example that returns an object with a single string property.
angular.module('app', ['ngDialog'])
.controller('ctrl', ($scope, ngDialog) => {
$scope.returnedValue = "";
$scope.openModal = function() {
var newClassDialog = ngDialog.open({
template: 'dialogTemplate',
closeByEscape: false,
controller: 'dialogCtrl',
className: 'ngdialog-theme-default',
width: 600
});
newClassDialog.closePromise.then(function(data) {
$scope.returnedValue = data.value.result;
});
};
})
.controller('dialogCtrl', ($scope, ngDialog) => {
var id = ngDialog.getOpenDialogs()[0];
$scope.returnValue = "";
$scope.close = () => {
ngDialog.close(id, { result: $scope.returnValue });
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/js/ngDialog.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/css/ngDialog.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/css/ngDialog-theme-default.min.css">
<div ng-app="app" ng-controller="ctrl">
<button ng-click="openModal()">Open Modal</button>
<p>Returned from dialog: {{ returnedValue }}</p>
<script type="text/ng-template" id="dialogTemplate">
<h1>ngDialog Sample</h1>
<p>
<label>Enter a value to return: </label>
<input type="text" ng-model="returnValue" />
</p>
<p><button ng-click="close()">Close</button></p>
</script>
</div>
This might work (can't test it unless you can share a plunker):
.controller('configManagementCtrl', ['$scope', 'deConfigService', 'ngDialog', '$state', 'notificationService',
function ($scope, deConfigService, ngDialog, $state, notificationService) {
$scope.loadDetails = function () {
....
};
$scope.openModal = function () {
$scope.newClassDialog = ngDialog.open({
template: 'views/modals/newClassModal.html',
closeByEscape: false,
controller: 'newClassController',
className: 'ngdialog-theme-default',
width: 600
});
$scope.newClassDialog.closePromise.then(function (data) {
console.log(data);
if (data.passBackData.value === 2) {
$scope.loadDetails();
// $state.go('app.config', {}, {reload: true, inherit: false});
// $scope.loadDetails();
}
});
};
}])
and in the other controller:
.controller('newClassController', ['$scope', 'ngDialog', 'deConfigService', 'notificationService',
function ($scope, ngDialog, deConfigService, notificationService) {
$scope.classObj = {};
var passBackData = [];
$scope.cancel = function () {
passBackData.push({'closeVal': 1});
console.log(passBackData);
$parent.$scope.newClassDialog.close(1, passBackData);
};
$scope.create = function (isFormValid) {
if (isFormValid) {
$scope.classObj.added_dt = (new Date()).toISOString();
$scope.classObj.class_id = 0;
deConfigService.createClass($scope.classObj, function (response) {
if (response.data) {
console.log(response.data);
passBackData.push(response.data.data);
notificationService.addSuccess('Class created successfully');
}
else {
notificationService.addError('Error!! Please try later');
}
});
$parent.$scope.newClassDialog.close(1, 2);
}
};
}])
On the Link below on plunker, I am trying to do a simple page connecting view 1 to view 2.
On view 1 we can type a text which will be shown on View2.
My difficulty is trying to understand how I can connect the Controller1 mentioned in the $stateProviderState, to the
Controller1.js, to the view. I find it difficult to understand how the
factory works, how to do the injection.
Could anyone explain to me? Thank you.
Plnkr - Linking pages using ui-router
//app.module.js
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/View1");
$stateProvider
.state("View1", {
url: "/View1",
templateUrl: "View1.html",
view: {
controller: 'Controller1'
}
})
.state("View2", {
url: "/View2",
templateUrl: "View2.html",
view: {
controller: 'Controller2'
}
});
});
//Controller1.js
(function() {
'use strict';
angular
.module("myApp")
.factory('shareFactory', shareFactory)
.controller('Controller1', Controller1);
function Controller1(shareFactory, $scope, $http) {
var vm = this;
vm.textView1 = "SomethingToStartWith";
function getView1() {
shareFactory.getData()
.then(function(response) {
if (response.data) {
vm.textView1 = response.data;
console.log(vm.textView1);
} else {
console.log("Something was wrong");
return;
}
}, function(response) {
console.log("Entered this Error function");
});
}
}
});
//Index.html
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script src="https://code.angularjs.org/1.5.5/angular.js" data-semver="1.5.5" data-require="angularjs#1.5.5"></script>
<script data-require="angular.js#<2" data-semver="1.5.7" src="https://code.angularjs.org/1.5.7/angular.js"></script>
<script data-require="ui-router#1.0.0-alpha.5" data-semver="1.0.0-alpha.5" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-alpha.5/angular-ui-router.js"></script>
<script src="app.module.js"></script>
<script src="Controller1.js"></script>
<script src="share.factory.js"></script>
</head>
<body >
<div class="header" ng-style="{background:'red'}">header</div>
<div data-ui-view=""></div>
<div class="footer" ng-style="{background:'blue'}">footer</div>
</body>
</html>
//share.factory.js
(function() {
angular
.module("myApp")
.factory('shareFactory', shareFactory);
function shareFactory() {
var data = '';
return {
getData: function() {
return data;
},
setData: function(newData) {
data = newData;
}
};
}
})();
Maybe code explains itself?
Below code forked from your initial plunk can be found here http://plnkr.co/edit/WLe3TLTa6DKWUQ21lK3P
JavaScript
angular.module('myApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('', 'view1');
// set up states
// no need to specify controllers in templates
$stateProvider
.state('view1', {
url: '/view1',
templateUrl: 'view1.html',
controller: 'Controller1',
controllerAs: 'vm'
})
.state('view2', {
url: '/view2',
templateUrl: 'view2.html',
controller: 'Controller2',
controllerAs: 'vm'
});
})
// factory, shared data
.factory('shareFactory', function($q) {
var data = 'initial value';
// mock $http using $q which returns
// resolved/rejected promise, as would $http
return {
getData: function() {
return $q.when(data); // resolve
},
setData: function(val) {
if (val.length > 0) {
data = val;
return $q.when(); // resolve
} else {
return $q.reject('value can\'t be empty'); // reject
}
}
};
})
.controller('Controller1', function(shareFactory, $state) {
var vm = this;
// because async
shareFactory.getData()
.then(function(data) {
vm.data = data;
});
vm.set = function(data) {
shareFactory.setData(data)
.then(function() {
vm.error = null;
$state.go('view2');
})
.catch(function(e) {
vm.error = e;
});
};
})
.controller('Controller2', function(shareFactory) {
var vm = this;
shareFactory.getData()
.then(function(data) {
vm.data = data;
})
.catch(function(e) {
console.log(e);
});
});
index.html
<body >
<div data-ui-view></div>
</body>
view1.html
<div>
<h1>view1</h1>
<label>Enter a value: </label>
<input type="text"
ng-model="vm.data">
<input type="button"
class="btn btn-default"
value="Go to view2"
ng-click="vm.set(vm.data)">
<pre ng-bind="vm.error"></pre>
</div>
view2.html
<div>
<h1>view2</h1>
The value set in view1 is: <b ng-bind="vm.data"></b>
<input type="button"
class="btn btn-default"
value="Go to view1"
ui-sref="view1">
</div>
Check the plunker. Injecting factory to controller, controller to main module and ui-routing
Check this
html
<div class="header" ng-style="{background:'red'}">header</div>
<div ui-view></div>
<div class="footer" ng-style="{background:'blue'}">footer</div>
main Js
var myApp = angular.module("myApp", ['ui.router','ConrollerApp']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/View1");
$stateProvider
.state("View1", {
url: "/View1",
templateUrl: "View1.html"
})
.state("View2", {
url: "/View2",
templateUrl: "View2.html"
});
});
Controller
var ctrl=angular.module("ConrollerApp",["Factory"])
ctrl.controller("AppController",function($scope,AppFactory){
$scope.data=AppFactory.useData();
})
Factory
var factoryapp=angular.module("Factory",[])
factoryapp.factory("AppFactory",function(){
return{
useData:function(){
var x=10;
return x;
}
}
})`
I have two directives that reference the same parent variable. The first directive is a dropdown. The second directive is a table. What I'm trying to accomplish is this: when a selection is made on the dropdown, the parent variable will change. The second directive using $scope.$watch will detect this change and load the data to the table. Problem is that the second directive is not detecting the change. I'm not understanding why.
// home.html
<div>
<directive-one testid="home.changevalue"></directive-one>
<br />
<directive-two testid="home.changevalue"></directive-two>
</div>
// search.directive.html
<div style="margin-top:5px;margin-left:25px;">
<div class="row" style="margin-bottom:10px;">
<label for="searchoptions" style="margin-left:15px;">Food Items</label>
<br />
<select style="margin-left:15px;" name="searchoptions" id="searchoptions1" ng-model="searchFoodItems.fooditemid" ng-change="searchFoodItems.onSelectionChange()">
<option value="">Select ...</option>
<option ng-repeat="fooditem in searchFoodItems.fooditems" value="{{fooditem.entryid}}">{{fooditem.itemdesc}}</option>
</select>
<span>Food Item ID - {{searchFoodItems.fooditemid}}</span>
</div>
</div>
// list.directive.html
<div style="margin-top:5px;margin-left:30px;">
<table class="table table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Description</th>
<th>Discount</th>
</tr>
</thead>
<tfoot></tfoot>
<tbody>
<tr ng-repeat="row in listFoodItems.fullitemdescs">
<td>{{row.EntryId}}</td>
<td>{{row.ItemDesc}}</td>
<td>{{row.ItemDisc}}</td>
</tr>
</tbody>
</table>
</div>
JS -
// home.js
(function () {
'use strict';
angular
.module(testConstants.generateName(testConstants.appModule, testConstants.NAMETYPES.module))
.controller(testConstants.generateName('home', testConstants.NAMETYPES.controller), home);
home.$inject = ['$scope', '$location', '$routeParams', '$q', '$window', 'logger', 'dataservice'];
function home($scope, $location, $routeParams, $q, $window, logger, dataservice) {
var home = this;
home.changevalue = '';
}
})();
// search.js
(function () {
'use strict';
angular
.module(testConstants.generateName(testConstants.appModule, testConstants.NAMETYPES.module))
.directive(testConstants.generateName('directiveOne', testConstants.NAMETYPES.directive), searchFoodItems);
searchFoodItems.$inject = ['dataservice', 'logger'];
function searchFoodItems(dataservice, logger) {
var sfi = {
restrict: 'E',
templateUrl: 'App/search/search.directive.html',
scope: {
fooditemid: '='
},
link: function (scope, element, attrs, controller) { },
controller: searchFoodItemsController,
controllerAs: 'searchFoodItems'
}
return sfi;
}
searchFoodItemsController.$inject = ['$scope', 'dataservice', 'logger'];
function searchFoodItemsController($scope, dataservice, logger) {
var search = this;
search.fooditemid = '';
search.fooditems = [];
search.onSelectionChange = function () {
$scope.fooditemid = search.fooditemid;
}
activate();
function activate() {
loadFoodItems();
}
function loadFoodItems() {
return dataservice.getFoodItems().then(function (result) {
search.fooditems = result;
logger.log("search.directive.js = getFoodItems loaded");
});
}
}
})();
// list.js
(function () {
'use strict';
angular
.module(testConstants.generateName(testConstants.appModule, testConstants.NAMETYPES.module))
.directive(testConstants.generateName('directiveTwo', testConstants.NAMETYPES.directive), listFoodItems);
listFoodItems.$inject = ['dataservice', 'logger'];
function listFoodItems(dataservice, logger) {
var lfi = {
restrict: 'E',
templateUrl: 'App/list/list.directive.html',
scope: {
fooditemid: '='
},
link: function (scope, element, attrs, controller) { },
controller: listFoodItemsController,
controllerAs: 'listFoodItems'
}
return lfi;
}
listFoodItemsController.$inject = ['$scope', '$q', 'dataservice', 'logger'];
function listFoodItemsController($scope, $q, dataservice, logger) {
var list = this;
list.fullitemdescs = [];
activate();
function watchFoodItem() {
$scope.$watch("$scope.fooditemid", function (value) {
$q.all([load(value)]).then(function () { logger.log('list.directive.js - fooditemid changed'); });
});
}
function activate() {
watchFoodItem();
load($scope.fooditemid);
}
function load(id) {
if (id === '') {
loadFoodItems();
}
else {
loadFoodItem(id);
}
}
function loadFoodItems() {
return dataservice.getFoodDescDiscs().then(function (result) {
list.fullitemdescs = result;
logger.log("list.directive.js = getFoodItems loaded");
});
}
function loadFoodItem(id) {
return dataservice.getFoodDescDisc(id).then(function (result) {
list.fullitemdescs = result;
logger.log("list.directive.js = getFoodItem loaded");
});
}
}
})();
Remove function and $scope from watcher.
//function watchFoodItem() {
$scope.$watch("fooditemid", function (value) {
$q.all([load(value)]).then(function () { logger.log('list.directive.js - fooditemid changed'); });
});
// }
I'm writing a controller. This controller has to communicate with an other controller. But I don't know is it posible?
HTML:
<div data-ng-app="TestApp">
<div data-ng-controller="menuCtrl">
<ul>
<li> <a data-ng-click="Click()">
MenĂ¼1</a>
</li>
</ul>
</div>
<div data-ng-controller="pageCtrl">
<hr/>
<button data-ng-click="getText()">GetText</button>
<br/>
<strong data-ng-model="boldText"> {{boldText}}</strong>
</div>
JS:
var app = angular.module('TestApp', []);
app.controller('menuCtrl', function ($rootScope, $scope) {
$scope.Click = function () {
//???
};
})
.controller('pageCtrl', function ($rootScope, $scope) {
$scope.getText = function () {
$scope.boldText = 'tst';
};
});
I repaired sample on JSfiddle:sample
You can easily achieve that with broadcasting:
var app = angular.module('TestApp', []);
app.controller('menuCtrl', function ($rootScope, $scope) {
$scope.Click = function () {
$scope.$broadcast('MyClickEvent', {
someProp: 'Clicking data!' // send whatever you want
});
};
})
.controller('pageCtrl', function ($rootScope, $scope) {
$scope.getText = function () {
$scope.boldText = 'tst';
};
$scope.$on('MyClickEvent', function (event, data) {
console.log(data); // 'Data to send'
});
});
Using the events broadcast, we can pass the value form one controller to another
app.controller('menuCtrl', function ($rootScope, $scope) {
$scope.Click = function () {
var valueToPass = "value";
$rootScope.$broadcast('eventMenuCtrl', valueToPass);
};
})
.controller('pageCtrl', function ($rootScope, $scope) {
$scope.getText = function () {
$scope.boldText = 'tst';
};
$scope.$on('eventMenuCtrl', function(event, value) {
$scope.boldText = value;
})
});
http://jsfiddle.net/q2yn9jqv/4/
I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here