假设我的HTML就像:
<body myDirective ng-controller="ContentCtrl">
<section id="content">
</section>
<footer ng-controller="FooterCtrl" myFooterDirective>
<div id="toolbar">
<div id="btn_home"></div>
</div>
</footer>
</body>
如何设置myDirective
来更改<footer>
元素,使其具有额外的子元素?像:
<footer ng-controller="FooterCtrl" myFooterDirective>
<div id="toolbar">
<div id="btn_home"></div>
<div id="customAddedChild"></div>
</div>
</footer>
我应该使用myFooterDirective
还是FooterCtrl
?或两者都没有,只搜索elem.find('toolbar')
或类似的内容?
修改 这是默认情况下工具栏代码实际包含的内容,我需要将其更改为仅设置为myDirective的1个项目(面对我所做的每个项目:projectProjectName,我还设置myApp.value('project',ProjectName)等等。
<div id="toolbar">
<button id="btn_home" class="btn btn-default" style="margin-left: 50px" ng-click="goHome('<?=$this->url('application/default', ['project' => $this->project])?>')">
<div class="btn_img" style="background-image: url('/images/home.png')"></div>
</button>
<button id="btn_back" class="btn btn-default" style="margin-left: 50px; display: none" ng-click="goBack()">
<div class="btn_img" style="background-image: url('/images/back.png')"></div>
</button>
<?php if (count($this->config['langs']) > 1):?>
<?php $i = 0;?>
<?php foreach ($this->config['langs'] as $lang):?>
<?php
$flag = $lang;
switch ($lang) {
case 'en':
$flag = 'gb';
break;
}
?>
<div class="flag-button pull-right" <?php echo $i == 0 ? 'style="margin-right:50px"' : null?>>
<a href="<?=$this->url('application/default', ['project' => $this->project], ['query' => ['lang' => $lang]])?>">
<div class="flag-icon-background flag-icon-<?=$flag?> flag"></div>
</a>
</div>
<?php $i++;?>
<?php endforeach?>
<?php endif?>
</div>
答案 0 :(得分:0)
真正正确的角度方法是使用页脚指令,为元素添加简单的ng-repeat。元素列表将由指令初始化。
阿卡:
<footer my-footer-directive>
<div id="toolbar">
<div ng-repeat="footerEl in footerElements" id="footerEl.id" ng-click="footeEl.action()"></div>
</div>
</footer>
指令:
module.directive("myFooterDirective", function() {
return {
restrict : "A",
scope : true,
link : function($scope, $el, $attrs) {
$scope.footerElements = [
{
id : "btn_home",
action : function() {
// do something
}
}
];
// insert other elements here depending on you needs and/or app logic
}
}
});
当然,这要求每个元素都具有相同的html表示/可以通过编程方式表示元素。
肮脏的方法是:
<footer my-footer-directive>
<div id="toolbar">
<div id="btn_home"></div>
</div>
</footer>
和
module.directive("myFooterDirective", function() {
return {
restrict : "A",
scope : true,
link : function($scope, $el, $attrs) {
var myDirtyInjectedDomElement = $("<i-am-ugly/>");
// maybe compile it here if this is not only an ugly html but an ugly dynamic element, see $compile if needed
$el.find("#toolbar").append(myDirtyInjectedDomElement);
}
}
});
由于评论而编辑:
以下是仅使用ng-if:
的一个可选元素 <footer my-footer-directive>
<div id="toolbar">
<div id="btn_home"></div>
<div id="my_optional_element" ng-if="showTheOptional"></div>
</div>
</footer>
和
module.directive("myFooterDirective", function() {
return {
restrict : "A",
scope : true,
link : function($scope, $el, $attrs) {
$scope.showTheOptional = true; // or false, or 42
}
}
});