How to call controller's any function in directive in angularJs
I'm trying to call parent controller's function, which has not much to do with the directive, when directive's bind value has changed.
I've been looking through the Q&A in stack, but all of them are related to passing a value from directive to controller, which is not my case.
I thought my case was generally common, the scenario is that: display complex objects in a loop, one of property of object bind on a directive. and when the property has changed, do-something with the updated complex object.
However in my code, it prints the old object value instead of updated one. My guess is that my update function is called before $digest process has completed.
any suggestions?
plunker example: https://plnkr.co/edit/bWGxEmJjNmiKCkRZTqOp?p=preview
here is the Controller code:
var $ctrl = this;
$ctrl.items = [
{id: 1, value: 10}, {id: 2, value: 20}, {id: 3, value: 30}
];
$ctrl.update = function(item){
//trying to update item after changing
console.log("updated item is: " + angular.toJson(item));
};
Here is the directive code:
var controller = function($scope){
var $ctrl = this;
$ctrl.clicked = function(){
$ctrl.value = $ctrl.value + 1;
//calling the bind on-change function defined in controller
$ctrl.onChange();
}
};
return {
restrict: 'E',
scope: {
value: '=',
onChange: '&'
},
controller: controller,
controllerAs: '$ctrl',
bindToController: true,
templateUrl: 'directive.html'
};
and Html looks like this:
<div ng-repeat="item in mc.items">
<my-directive value="item.value" on-change="mc.update(item)"></my-directive>
</div>
and directive template:
<button type="button" ng-click="$ctrl.clicked()">{{$ctrl.value}}</button>
You are correct that the update function is called before
$digestprocess has completed.One approach is to update the value with
ng-modelandng-change:JS:
With this approach, the ngModelController will update the value before calling ng-change.
The Demo
require: {ngModelCtrl: 'ngModel'}binds theng-modelcontroller API to the directive controller with the namengModelCtrl.scope: {value: '<ngModel'}creates a one-way binding of theng-modelattribute to the controller with the namevalue.For more information, see
Using
ng-modelenables integration with the validation API of the ngFormController. One can create custom form components with multiple inputs.For more information, see
ngModel)