Reputation: 2541
I have written a directive to validate certain binded value and modify it before executing the action on the button. But any value update in directive value is not reflected in the parent scope. I have used (=) in the directive so my assumption is it will update the parent scope as well.
Let me know what I am doing wrong. Have attached the images.
This is the view where both parent and the directive sharing the same text value.
The result value assigned to the validate text is not reflected in the parent selected node. while the ok function is executed.
I do see the value getting updated back in the text area. But dont know why it is not updated when the ok funciton is executed.
I have tried $timeout, $evalAsync on the scope.ngClick with no success.
Upvotes: 2
Views: 1909
Reputation: 8789
Changes that are made inside event handlers of elements of custom directives are not triggering Angular's digest cycle. Therefore you need to notify Angular that scope has been changed (by calling scope.$digest()
or scope.$apply()
). Another thing I have noticed is that method ok()
is called twice: once inside Angular's ngClick
directive and second time inside your directive. If it is not a desired behavior, remove it from your directive. Here is some working code:
HTML
<body ng-controller="myController">
<textarea ng-model="selected.note"></textarea>
<button type="button" validatetext="selected.note" ng-click="ok()">Click Me!</button>
</body>
JavaScript
angular.module('online-desktop', []).
controller('myController', ['$scope', function($scope) {
$scope.selected = {
note: 'old value'
};
$scope.ok = function() {
alert($scope.selected.note);
};
}]).
directive('validatetext', [function() {
return {
scope: {
validatetext: '='
},
link: function(scope, element, attr) {
element.on('click', function() {
scope.$apply(function() { // <= change scope properties inside scope.$apply()
scope.validatetext = 'some new value';
});
});
}
}
}]);
Plunker: http://plnkr.co/edit/rmJVBzjIeiVcoQUV79z2?p=preview
Upvotes: 1
Reputation: 1930
I would suggest you try a $rootScope.$broadcast from the directive and catch it in the parent with $scope.$on
//directive
$rootScope.$broadcast("valueUpdated", result);
//parent
$scope.$on("valueUpdated", function(event, result){
//update the value here
});
You can also probably use $scope.$emit instead of $rootScope.$broadcast.
Upvotes: 0