I am having a rich text box with all the style controls.
When I enter a new text in it - it saves.
When I make any changes in the content (text) along with some styles like color highlighting and bold text - it saves the changed text and styles.
But, when I just make style changes without any content change - it won't save those style changes.
I am using $watch to compare new value and old value.
How to make it work even for style changes?
The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.
Change detection is invoked automatically using zones. The framework hooks into internal browser API calls and performs CD after asynchronous events. Two-way data binding is supported which means that single pass of change detection is not enough. AngularJS runs digest cycles until the model stabilizes.
$digest() is faster than $apply(), since $apply() triggers watchers on the entire scope chain while $digest() triggers watchers on the current scope and its children(if it has).
Definition and UsageThe ng-change event is triggered at every change in the value. It will not wait until all changes are made, or when the input field loses focus. The ng-change event is only triggered if there is a actual change in the input value, and not if the change was made from a JavaScript.
angular.module("app",[]).directive('spyStyle', [function () {
return {
link: function (scope, element, attrs) {
scope.$watch(function () {
return element.css(attrs['spyAttribute']);
}, styleChangedCallBack,
true);
function styleChangedCallBack(newValue, oldValue) {
if (newValue !== oldValue) {
// do something interesting here
}
}
}
};
}]);
In your HTML:
<div spy-style spy-attribute="height" >
In case you want to execute custom functions outside the directive:
<div spy-style="functionNameToExecute" spy-attribute="height" >
In your Directive code make this change:
angular.module("app",[]).directive('spyStyle', [function () {
return {
link: function (scope, element, attrs) {
scope.$watch(function () {
return element.css(attrs['spyAttribute']);
}, styleChangedCallBack,
true);
function styleChangedCallBack(newValue, oldValue) {
if (newValue !== oldValue) {
// do something interesting here
// invoking callback function:
scope[attrs['spyStyle']](newValue);
}
}
}
};
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With