I need to update a controller variable from a child directive, but even after updating the controller variable, the value doesn't change in the view. Should I use $scope.$apply() or $digest?
Here is my code: http://plnkr.co/edit/zTKzofwjPfg9eXmgmi8s?p=preview
JavaScript file:
var app = angular.module('app', []);
app.controller('parentController', function($scope) {
this.myVar = 'Hello from parent';
this.refreshMyVar = function(data) {
this.myVar = data.name;
console.log('>> this.myVar', this.myVar);
};
});
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
template: '<input type="file" />',
bindToController: {
attrFromParent: '='
},
controller: 'directiveController as directiveCtrl',
link: function(scope, el, attr, ctrl) {
el.bind('change', function(e) {
ctrl.onChange(e.target.files[0]);
});
}
};
});
app.controller('directiveController', function() {
this.onChange = function(file) {
this.attrFromParent(file);
};
});
HTML file:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<body>
<div ng-app="app" ng-controller="parentController as parentCtrl">
<h1> >> {{parentCtrl.myVar}}</h1>
<p><my-directive attr-from-parent="parentCtrl.refreshMyVar" /></p>
</div>
</body>
</html>
If you have any suggestions on how to improve my code, please share them.
UPDATE
app.controller('parentController', function($scope) {
this.myVar = 'Hello from parent';
this.refreshMyVar = data => {
this.myVar = data.name;
console.log('>> this.myVar', this);
$scope.$parent.$apply(); // This resolved my issue
};
});
$scope.$parent.$apply() solved my issue, but I'm open to other suggestions.