I'm having trouble with variable scoping and/or passing data between controllers. One controller is nested inside the other. When one of the values of the nested controller changes, I want that to be reflected in its parent controller. This is not happening. I think I have to create a service to pass data from the child controller to the parent controller, but I'm not sure how to go about that. I started to write some code, but it didn't work when I tried to implement it. First I'll give the code without the service.
The parent and child controllers are contained in their own submodules, and the app is dependent on both of these submodules. The service would be defined in the child controller's module. I'm not sure if this matters, or if the scope of the modules matters either since they are all embedded in the same app.
I'd like to pass the value of $scope.activeOn
from the child controller to the parent controller whenever its value changes. This would be taken care of by the switchProcessing();
function. I'm trying to simulate a button toggle and progress bar (custom toggle
directive). When the button is switched to off, then the progress bar goes to zero. Otherwise, if its on, it shows the value generated by the backend.
index.html
<div ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
<toggle on="activeOn" off="activeOff" ng-click="switchProcessing();"></toggle>
</div>
</div>
toggle template
<div class="btn-group btn-toggle">
<button class="btn btn-sm" ng-class="{'btn-success':on, 'btn-default':!on}">ON</button>
<button class="btn btn-sm" ng-class="{'btn-danger':off, 'btn-default':!off}">OFF</button>
</div>
parentCtrl.js
angular
.module('app.parent')
.controller('ParentCtrl', ParentCtrl);
function ParentCtrl($scope, $http, $timeout) {
$scope.max = 20000;
//$scope.activeOn = true;
$scope.getData = function() {
$http.get('http://url/to/data')
.success(function(data, status) {
$scope.dynamic = data[0].currentDepth;
$scope.xsiteStatus = status;
});
};
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getData();
$scope.intervalFunction();
}, 10000);
};
$scope.switchProcessing = function() {
if($scope.activeOn === true) {
$scope.activeOn = false;
$scope.dynamic = 0;
} else {
$scope.activeOn = true;
}
};
$scope.intervalFunction();
}
childCtrl.js
angular
.module('app.child')
.controller('ChildCtrl', ChildCtrl);
function ChildCtrl($scope) {
$scope.activeOn = true;
$scope.activeOff = false;
}
app.js
angular.module('app', ['app.parent', 'app.child']);
The service I have coded so far...
angular.module('opsConsole.child')
.service('buttonToggleService', buttonToggleService);
function buttonToggleService() {
var buttonSwitch = true;
var getButtonStatus = function(buttonSwitch) {
return buttonSwitch;
};
return {
getButtonStatus: getButtonStatus
};
}