bcherny
bcherny

Reputation: 3172

Prevent angular directive from compiling more than once

I have a directive that I manually render once:

let html = '<div>'
let scope = $rootScope.$new(true)
scope.foo = 42

let element = $compile(html)($scope)
element.appendTo(container)

After that, I don't want it to ever re-render, even if there is a $digest on the $rootScope. Is that possible with Angular?

Upvotes: 2

Views: 519

Answers (1)

scniro
scniro

Reputation: 16979

If you mean you wish to remove all bindings on your directive, you can call $destroy to remove any bindings on you have. Consider this example, where both directives bind message

<input ng-model="message" id="dirA" dir-a />
<input ng-model="message" id="dirB" dir-b />
<input ng-model="message" />

app.directive('dirA', [function () {
    return {
        scope: true,
        restrict: 'A',
        link: function (scope, elem, attrs) {
        }
    }
}]);

app.directive('dirB', [function () {
    return {
        scope: true,
        restrict: 'A',
        link: function (scope, elem, attrs) {
        }
    }
}]);

app.controller('ctrl', ['$scope', '$timeout', function($scope, $timeout) {

    $scope.message = 'hello'

    $timeout(function(){
        // destroy scope for dirA
        angular.element(document.getElementById('dirA')).scope().$destroy()
    })
}]);

JSFiddle Link

Upvotes: 1

Related Questions