2016-04-28 52 views
2

在以下程序中,功能应该如下 - >控制器,指令控制器,编译,链接。但是,编译函数似乎有一些错误。控制器,指令控制器,编译,链接 - 工作流程(编译功能不起作用)

<html> 
<head> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js" ></script> 
</head> 
<body ng-app="myApp" ng-controller="myCtrl"> 
<people></people> 
<script> 
//1 module declaration 
var app = angular.module("myApp",[]); 
//3 controller declaration 
app.controller('myCtrl',function($scope){ 
    //before going to directive 
    $scope.name = "One"; 
}); 
//5 directives declaration 
app.directive('people',function(){ 
    return{ 
     restrict: 'E', 
     template: '<div>{{name}}</div>', 
     //before compilation 
     controller: function($scope, $element){ 
      $scope.name = $scope.name + "Two"; 
     }, 
     compile: function($scope, $element){ 
      $scope.name = $scope.name + "Three"; 
     }, 
     //after compilation 
     link: function($scope, el, attr){ 
      $scope.name = $scope.name + "Four" 
     } 
    } 
}); 
</script> 
</body> 
</html> 

后市展望:

OneTwoThreeFour 

结果

OneTwo 

但是,如果我从指令取出编译功能,我得到以下结果:

OneTwoFour 

有什么不对的编译功能,它并没有在$ scope.name呈现“三化”?从Angular documentation采取

+1

希望这不应该是一个问题,在你的代码,但这里的拼写错误限制:'E',' –

+0

Nopse,抱歉是错字。 – Deadpool

+0

下面的答案有帮助吗?让我知道你是否需要任何进一步的信息。 – carlcheel

回答

2

片断:仅当没有定义属性编译

链路属性被使用。做一些前期和后期编辑,返回你的编译功能如下:

function compile(tElement, tAttrs, transclude) { 
    return { 
     pre: function preLink(scope, iElement, iAttrs, controller) { ... }, 
     post: function postLink(scope, iElement, iAttrs, controller) { ... } 
    } 
} 

的$ scope变量在编译功能无法使用,而无需使用预链接或postLink。

function compile(tElement, tAttrs, transclude) { ... } 
  • tElement - 模板元素 - 在该指令已申报的元素。仅对元素和子元素进行模板转换是安全的。

  • tAttrs - 模板属性 - 在此元素上声明的属性的规范化列表在所有指令编译函数之间共享。

  • transclude - 一个transclude链接功能已废弃!]:功能(范围,cloneLinkingFn)

下面就来演示一个例子:https://plnkr.co/edit/CCnLFJX8D7sbKobuF1GS?p=preview

+0

宾果.....这就是我期待的! – Deadpool

相关问题