Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

feat(Attributes): added support for attributes observing deregistration #5609

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/ng/compile.js
Original file line number Diff line number Diff line change
@@ -769,7 +769,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
* @param {function(interpolatedValue)} fn Function that will be called whenever
the interpolated value of the attribute changes.
* See the {@link guide/directive#Attributes Directives} guide for more info.
* @returns {function()} the `fn` parameter.
* @returns {function()} Returns a deregistration function for this observer.
*/
$observe: function(key, fn) {
var attrs = this,
@@ -783,7 +783,10 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
fn(attrs[key]);
}
});
return fn;

return function() {
arrayRemove(listeners, fn);
};
}
};

17 changes: 14 additions & 3 deletions test/ng/compileSpec.js
Original file line number Diff line number Diff line change
@@ -1749,15 +1749,14 @@ describe('$compile', function() {


describe('interpolation', function() {
var observeSpy, directiveAttrs;
var observeSpy, directiveAttrs, deregisterObserver;

beforeEach(module(function() {
directive('observer', function() {
return function(scope, elm, attr) {
directiveAttrs = attr;
observeSpy = jasmine.createSpy('$observe attr');

expect(attr.$observe('someAttr', observeSpy)).toBe(observeSpy);
deregisterObserver = attr.$observe('someAttr', observeSpy);
};
});
directive('replaceSomeAttr', valueFn({
@@ -1855,6 +1854,18 @@ describe('$compile', function() {
}));


it('should return a deregistration function while observing an attribute', inject(function($rootScope, $compile) {
$compile('<div some-attr="{{value}}" observer></div>')($rootScope);

$rootScope.$apply('value = "first-value"');
expect(observeSpy).toHaveBeenCalledWith('first-value');

deregisterObserver();
$rootScope.$apply('value = "new-value"');
expect(observeSpy).not.toHaveBeenCalledWith('new-value');
}));


it('should set interpolated attrs to initial interpolation value', inject(function($rootScope, $compile) {
$rootScope.whatever = 'test value';
$compile('<div some-attr="{{whatever}}" observer></div>')($rootScope);