javascript - 不要以 Angular 方式工作指令

标签 javascript angularjs

我才开始学习 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 工作,我测试过。 结果中的代码没有打印任何内容(任何人都可以帮助我吗?

附注 如果您能解释一下这个 transinclude : 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

嵌入: 使用 transinclude 允许您将 HTML 注入(inject)到指令中。在指令本身中,您可以放置​​ ng-transclude指令和 Angular 会将其替换为您要注入(inject)的 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>

Angular 将在您放置 ng-transclude 的位置插入文本“says Hello”指令模板中的指令。这是plnkr显示这个。

关于javascript - 不要以 Angular 方式工作指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32158502/

相关文章:

javascript - 如何在不同的复选框 Angular 之间切换

angularjs - 无法使用键盘以特定高度导航 angular-ui bootstrap typeahead

c# - jsonreaderexception 遇到意外字符

javascript - 在 ng-repeat 期间构建 AngularJS 变量名称

javascript - HTML 5 Canvas 画线?

javascript - casperjs,可能需要另一种点击方法?

javascript - 解构 undefined object 数组

javascript - Jquery 实时替换文本不起作用

javascript - 在 .append 之后更改属性

javascript - Angular UI Modal - 如果成功触发器在表单标签内,则 ModalInstance 未定义