2017-07-09 6 views
1

角度js指令で置き換える前に元のマークアップを取得するにはどうすればよいですか?この質問は既に尋ねられていますが、ソリューションは私にとってはうまくいかないので、私はこれを投稿しています。また、角度jsチームが新しい方法を導入したかどうかを知りたいと思っています。angularjs指令に置き換えられる前の元のテンプレートを取得

これは私がこれまでにしようとしているものです:

function $block($compile) { 

    var html = '<div>new content</div>'; 

    return { 
     restrict: 'E', 
     template: function(element, attrs) { 
     console.log(element); // still getting the new element 
     return html; 
     }, 
     link: function(scope, element, attrs) { 
      console.log(element) 
     } 
    }; 

    } 

    angular.module('directive', []) 
    .directive('myDirective', $block); 

は、どのように私は古いテンプレートを取得することができますし、新しいものと交換してください?

答えて

0

angular.module('directive', []) 
 
    .directive('myDirective', function(){ 
 
     return { 
 
     restrict: 'A', 
 
     template: '<div>new content</div>', 
 
     link: function(scope, element, attrs) { 
 
     }, 
 
     compile:function(scope,element){ 
 
     console.log(element.$$element[0].outerHTML) 
 
     
 
     } 
 
    }; 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
 
<html> 
 
<body ng-app="directive"> 
 
<div style="background-color:red;" my-directive>Hello</div> 
 
</body> 
 
</html>

+0

これはまた、新しいコンテンツだけでなく、古いものを出力します。 –

+0

コード全体を貼り付ける代わりに、コードの内容を説明してください。 – Mistalis

1

ときconsole.logオブジェクト、ブラウザは、それが表示された時点で、コンテンツ値を表示します。それがログに記録された時点ではありません。それがデベロッパーコンソールの仕組みです。

あなたは彼らが異なっていることがわかりますinnerHTMLをログインした場合:

angular.module('directive', []) 
 

 
    .directive('myDirective', $block); 
 
    
 
    function $block($compile) { 
 

 
    var html = '<div>new content</div>'; 
 

 
    return { 
 
     restrict: 'E', 
 
     template: function(element, attrs) { 
 
     console.log(element[0].innerHTML); 
 
     return html; 
 
     }, 
 
     link: function(scope, element, attrs) { 
 
      console.log(element[0].innerHTML); 
 
     } 
 
    }; 
 

 
    }
<script src="//unpkg.com/angular/angular.js"></script> 
 
    <body ng-app=directive> 
 
    <h1>Directive Demo</h1> 
 
    <my-directive><div>Old Content</div> 
 
    </my-directive> 
 
    </body>

関連する問題