簡體   English   中英

角鏈接函數中作用域變量的作用范圍是什么?

[英]what will be the scope of scope variable in link function in angular?

var $directive = angular.module('myApp', []);
$directive.directive('myDirective', function(){
   return {
      restrict: 'E',
      template: '<h4>{{title}}</h4>'
      compile: function(element, attrs){
        console.log('this is compile'); 
        return function link(scope, element, attrs){ 
           element.on('click', function(){
              scope.title = 'My Directive 2 on click'; 
              scope.dataPoint(scope.title);
           }); 
        }; 
      },
     controller: function($scope){
        $scope.title = "My Directive";
         $scope.dataPoint = function(title){
             $scope.title = title;
         };
     }
  };
});
<my-directive></my-directive>

在上面的代碼段中,我試圖更改單擊元素時在控制器中聲明的范圍變量標題,但未顯示任何更改。

你們能幫我嗎? 提前致謝..

您必須在scope.$apply內分配標題。 scope.$apply()將使單擊處理程序使Angular進入digest周期

link: function(scope, element, attr, ctrl) {
    element.on('click', function() {
        scope.$apply(function() {
            scope.title = 'My Directive 2 on click'; 
        });
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM