I am only start study angular and want understand why my code doesn't work. Code:
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>'
}
});
In my html
<name data-first="Jack" data-second="Nollan"></name>
<name data-first="Chris" data-second="John"></name>
I include angular and my scripts. Angular work, i test. My code in result print nothing ( Can anybody help me?
PS If you can explain what do this transclude : true,
i will be very grateful.
Firstly, template is spelt incorrectly in the directive and secondly, in the HTML you need to use {{ fullName }}
instead of [[ fullName ]]
Your directive should be:
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>'
}
});
Here is a plnkr
Transclude: Using transclude allows you to inject HTML into your directive. In the directive itself you can place the ng-transclude
directive and Angular will replace this with the HTML you want to inject.
In your example if you wanted to display the text 'says hello' after the name of the person you could change your directive to this:
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>'
}
});
In your HTML you can then enter the text in the <name />
element like so:
<name first="Jack" second="Nollan"> says Hello</name>
Angular will then insert the text 'says Hello' wherever you have placed the ng-transclude
directive in your directive template. Here is a plnkr showing this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.