角度链接函数中范围变量的范围是什么?

时间:2014-04-16 10:16:59

标签: javascript angularjs angularjs-directive angularjs-scope

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>

在上面的代码片段中,我试图更改范围变量标题,我在控制器中点击了该元素,但它没有显示任何变化..?

你们可以帮帮我吗?提前谢谢..

1 个答案:

答案 0 :(得分:0)

您必须在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'; 
        });
    });
}