我正在使用自定义的“编译”指令来呈现HTML片段,我将其推送到一个工作得很好的div容器中。我遇到的一个问题是,似乎多次调用编译指令(3x)。我怎么能注意它只运行一次?
这是编译指令:
app.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
}]);
然后,在代码加载到div后,这会为玩家中的每个玩家创建三个按钮。
<div class="row">
<div class="col-md-1 mainpage-nav">
<ul>
<li ng-click="changePlane(1)" data-planeOrigin="1">
<span class="glyphicon glyphicon-home"></span>
<span>Overview</span>
</li>
<li ng-click="changePlane(2)" data-planeOrigin="2">
<span class="glyphicon glyphicon-user"></span>
<span>Players</span>
</li>
<li ng-click="changePlane(3)" data-planeOrigin="3">
<span class="glyphicon glyphicon-education"></span>
<span>Teams</span>
</li>
</ul>
</div>
<div class="col-md-11 mainpage-main" compile="mainPlane">
</div>
</div>
</div>
</div>
<!--
Overview
-->
<div data-plane="1" class="hidden">
<div class="row">
<div class="list-group">
<button type="button" class="list-group-item" ng-repeat="player in players">{{ player.user_name }}</button>
</div>
</div>
</div>
和js:
$scope.changePlane = function(planeID) {
$('[data-planeOrigin="'+currentPlane+'"]').removeClass("active");
currentPlane = planeID;
$('[data-planeOrigin="'+planeID+'"]').addClass("active");
var data = $('[data-plane='+planeID+']').html();
$scope.mainPlane = data;
};