防止角度指令多次编译

时间:2015-05-07 20:05:47

标签: javascript angularjs angularjs-directive

我有一个手动渲染一次的指令:

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

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

之后,即使$ rootScope上有$摘要,我也不希望它重新渲染。这对Angular有可能吗?

1 个答案:

答案 0 :(得分:1)

如果您的意思是希望删除指令中的所有绑定,则可以调用$destroy删除您拥有的任何绑定。考虑这个例子,其中两个指令绑定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