在角函数中,范围变量的范围是多少

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

本文关键字:变量 范围是 多少 范围 函数      更新时间:2023-09-26
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'; 
        });
    });
}