Don't work directive in angular

Don't work directive in angular

本文关键字:directive in angular work Don      更新时间:2023-09-26

我刚开始学习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>

我包括了angular和我的脚本。Angular work, i test。我的代码在结果打印什么(有人能帮助我吗?

注:如果你能解释一下这个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替换它。

在你的例子中,如果你想在人的名字之后显示文本'说你好',你可以将你的指令更改为:

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>

然后Angular会在指令模板中你放置ng-transclude指令的任何地方插入文本'说你好'。