如预期嵌套指令不起作用 [英] Nested directives don't work as expected
问题描述
我有一个通用的指令
- genericDirective
这是应该选择另一种特定的指令
that is supposed to choose another specific directive
- TYPE1指令,如果
obj.type ==TYPE1
- 2型指令,如果
obj.type ==2型
- type1 directive if
obj.type == "type1"
- type2 directive if
obj.type == "type2"
<div ng-controller="MainCtrl">
<div class="genericdirective" ng-repeat="obj in someArray"></div>
</div>
的JavaScript
var app = angular.module("myApp", []);
app.controller("MainCtrl", function ($scope) {
$scope.someArray = [
{type:"type1",title:"lorem"},
{type:"type2",title:"ipsum"},
{type:"type2",title:"dolor"}
];
});
app.directive("genericdirective", function(){
return{
restrict: "C",
template: "<div class='{{obj.type}}'>genericdirective</div>"
};
});
app.directive("type1", function(){
return{
restrict: "C",
template: "<div>type1</div>"
};
});
app.directive("type2", function(){
return{
restrict: "C",
template: "<div>type2</div>",
};
});
输出HTML
<div class="genericdirective ng-scope" ng-repeat="obj in someArray">
<!-- Not replaced by the actual directive -->
<div class="type1">genericdirective</div>
</div>
<div class="genericdirective ng-scope" ng-repeat="obj in someArray">
<!-- Not replaced by the actual directive -->
<div class="type2">genericdirective</div>
</div>
<div class="genericdirective ng-scope" ng-repeat="obj in someArray">
<!-- Not replaced by the actual directive -->
<div class="type2">genericdirective</div>
</div>
任何想法,为什么这些没有被实际的指令取代?
Any idea why these are not replaced by the actual directives?
推荐答案
通过使用收益
你的 genericDirective
app.directive("genericdirective", function(){
return{
restrict: "C",
template: "<div class='{{obj.type}}'>genericdirective</div>"
};
});
您在返回链接
功能。编译阶段后的链接阶段发生。所以,你的时间是解决这个模板,角不能编译你的孩子指示,再把它们连接。
You are returning the link
function. The link phase happens after the compile phase. So, by the time you are resolving this template, angular cannot "compile in" your child directives and then link them.
您需要定义一个函数编译并成立了当时的指示,以修改角度将考虑HTML。你需要连接的 $范围之前,操纵HTML的任何时间
,你大概是想在编译期进行更改。
You need to define a compile function and set up the directive at that time in order to modify the html that angular will consider. Any time that you need to manipulate the html before linking the $scope
, you probably are wanting to make changes during the compile phase.
要了解更多关于编译和链接请参见文档这里。标题为编译过程,并指令匹配,是非常有帮助的。
To read more about compile and link see the docs here. The section titled "Compilation process, and directive matching" is very helpful.
这篇关于如预期嵌套指令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!