[英]Don't work directive in angular
我只是开始学习角度知识,想了解为什么我的代码不起作用。 码:
var app = angular.module('app', ['appModule']).config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[').endSymbol(']]');});
var appModule = angular.module('appModule', []);
appModule.directive('name', function(){
return{
restrict : 'E',
scope : {},
//transclude : true, // it has HTML content
link : function(scope, element, attrs, controllers){
scope.fullName = attrs.first + " " + attrs.second
},
tempalte : '<h1>[[ fullName ]]</h1>'
}
});
在我的HTML中
<name data-first="Jack" data-second="Nollan"></name>
<name data-first="Chris" data-second="John"></name>
我包括角度和我的脚本。 有角的工作,我测试。 结果中的我的代码什么也没打印(有人可以帮我吗?
PS:如果您能解释一下这是什么意思transclude : true,
好的transclude : true,
我将不胜感激。
首先,指令中的模板拼写错误,其次,在HTML中,您需要使用{{ fullName }}
而不是[[ fullName ]]
您的指令应为:
var appModule = angular.module('appModule', []);
appModule.directive('name', function(){
return {
restrict : 'E',
scope : {},
//transclude : true, // it has HTML content
link : function(scope, element, attrs, controllers){
scope.fullName = attrs.first + " " + attrs.second
},
template : '<h1>{{ fullName }}</h1>'
}
});
这是一个plnkr
Transclude:使用transclude允许您将HTML注入指令中。 在指令本身中,您可以放置ng-transclude
指令,Angular会将其替换为您要注入的HTML。
在您的示例中,如果您想在人员名称后显示文本“ says hello”,则可以将指令更改为此:
var appModule = angular.module('appModule', []);
appModule.directive('name', function(){
return{
restrict : 'E',
scope : {},
transclude : true, // it has HTML content
link : function(scope, element, attrs, controllers){
scope.fullName = attrs.first + " " + attrs.second
},
template : '<h1>{{ fullName }} <ng-transclude></ng-transclude></h1>'
}
});
然后,您可以在HTML中的<name />
元素中输入文本,如下所示:
<name first="Jack" second="Nollan"> says Hello</name>
然后,只要将ng-transclude
指令放在指令模板中的任何位置,Angular都会插入文本“ says Hello”。 这是显示此内容的plnkr 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.