问题
I am trying to figure out how to create my own "one time binding", for Angularjs <= 1.2. I found this answer, describing how to create your own bindOnce directive. I do see that when using the following directive:
app.directive('bindOnce', function() {
return {
scope: true,
link: function( $scope ) {
setTimeout(function() {
$scope.$destroy();
}, 0);
}
}
});
Data is binded once. But, I can see that the $$watchers is still on. Take a look at the following JSBin - running the commented watcher count code on the console will reveal that the watchers are still alive.
EDIT: for some reason, when using the same directive with angular 1.3, the watcher count dod changed to be 0!!!
回答1:
Use the cleanup function to remove watchers:
function cleanup(element)
{
element.off().removeData();
var injector = currentSpec.$injector;
element.$injector = null;
// clean up jquery's fragment cache
angular.forEach(angular.element.fragments, function(val, key) {
delete angular.element.fragments[key];
});
angular.forEach(angular.callbacks, function(val, key)
{
delete angular.callbacks[key];
});
angular.callbacks.counter = 0;
}
Use a self-destructing service as a simple bind once:
function onetime()
{
/*...*/
onetime = Function;
}
angular.module('myApp').constant('bindonce', onetime);
angular.module('myApp').controller('foo', function($bindonce){
this.$inject = '$bindonce';
$scope.mybind = $bindonce();
}
Use the migration guide for reference to find breaking changes:
References
testabilityPatch.js
angular-mocks.js
AngularJS Developer Guide: Migration from Previous Versions
来源:https://stackoverflow.com/questions/27400422/angularjs-scope-destroy-doesnt-remove-watchers