I have a simple parent/child controller set up as follows:
<body ng-controller="ParentCtrl">
<section my-directive></section>
<div ng-controller="Child1Ctrl">
<button ng-click="child1()">Click Child1</button>
</div>
<br>
<div ng-controller="Child2Ctrl">
<button ng-click="child2()">Click Child2</button>
</div>
</body>
When i click on either button, from Child1Ctrl OR Child2Ctrl, i want the scopes within my-directive to be updated.
myDirective.js
app.directive('myDirective', function () {
var slider = {
initial : function() {
slider.clear();
$scope.slideHide = false;
$scope.slideShow = false;
},
clear: function() {
$scope.slideMessage = '';
$scope.slideError = false;
$scope.slideSuccess = false;
},
error: function(message) {
$scope.slideShow = true;
$scope.slideError = true;
$scope.slideMessage = message;
},
success: function(message) {
$scope.slideShow = true;
$scope.slideSuccess = true;
$scope.slideMessage = message;
}
}
return {
restrict: 'A',
replace: true,
transclude: true,
template: '<section class="slide">' +
'<div data-ng-class="{\'slide-show\' : slideShow, \'slide-error\' : slideError, \'slide-success\' : slideSuccess, \'slide-hide\' : slideHide}">' +
'<p>{{ slideMessage }}</p>' +
'</div>' +
'</section>'
}
}
);
And call within my child controllers:
app.controller('Child1Ctrl', function($scope) {
$scope.child1 = function () {
$scope.$parent.slider.initialise();
}
});
app.controller('Child2Ctrl', function($scope) {
$scope.child2 = function () {
$scope.$parent.slider.success('Display some text');
}
});
Update with fiddle:
http://jsfiddle.net/6uub3jqx/1/
If you click on the first set of buttons, the red/green ribbon appears.
If you click on the buttons withing the child1/2 controllers, there is no action.
Solution:
See fiddle: http://jsfiddle.net/6uub3jqx/2/
Essentially the child should send:
$scope.successChild1 = function(msg) {
$scope.$emit('successCh1', 'Some data');
};
And the parent should receive:
$scope.$on('successCh1', function (event, data) {
$scope.$broadcast('success', data);
});
Would rootscope be a better alternative?