当尝试从编译函数访问范围变量时,指令给出了错误

时间:2016-09-21 11:00:03

标签: angularjs

当我尝试为显示内容和工具提示制作指令但我需要在编译函数中初始化范围变量'name'。

sampleApp.directive('secondPage',function($compile){
    return {
        restrict:'E',
        template:'<h3>Second Page Directive Content Displaying using directive scope <u>{{name}}</u></h3>',
        scope:false,
        controller: function( $scope, $element, $attrs, $transclude ) {
            $scope.name = 'Angular Js';
        },
        compile: function (element, attrs) {

        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);              
          }
        };
        }       
    }

});

Html代码 -

<div ng-controller="MySecondController">
 <h2 ng-bind='message'></h2>
 <second-page name='Second Page'></second-page>
</div>

1 个答案:

答案 0 :(得分:0)

function post(scope, iElem, iAttrs){
    var name = iAttrs.name;
    $compile(iElem)(angular.extend(scope.$new(), {name: name}));
}