将回调绑定到没有隔离范围的指令

时间:2016-04-28 11:03:39

标签: javascript angularjs angularjs-directive

将回调函数绑定到指令时,使用正确的上下文执行此函数非常重要。现在,只要该指令具有隔离范围,就不存在问题

<bar-foo callback="mycontroller.callback()"></bar-foo>

和指令:

 ...
 scope:{
     callback: '&'
 },
 ...

如果没有隔离范围,我会从$ attrs attrubute

中提取回调
$scope.callback = $parse($attrs.callback)($scope);

但是,现在我做不到

 <bar-foo callback="mycontroller.callback()"></bar-foo>

因为它会直接执行回调。解决这个问题的首选方法是什么?

DEMO

3 个答案:

答案 0 :(得分:2)

首先在控制器中创建一个函数,该函数在此函数内显式设置this的值:

this.exportableCallback = this.callback.bind(this);

其中this.callback是您用于隔离范围的那个。

第二步是将其设置为属性

<hello-world callback="mycontroller.exportableCallback"></hello-world>

调用该功能,就像使用隔离范围一样。

请参阅fiddle

另一个选项(如果从控制器中删除this.callback)是

this.exportableCallback = function() {
  console.log(this.test);
}.bind(this);

如果要将参数传递给此函数:

this.exportableCallback = function() {
  console.log(arguments);
}.bind(this);

答案 1 :(得分:0)

由于这个范围不是隔离的,所以不仅仅是调用你想要的东西吗?

    .directive('helloWorld', function () {
    return {
        restrict: 'E',
        template: '<button ng-click="mycontroller.callback()">Not isolated</button>',
    }
});

然后只是调用你的指令?

<hello-world></hello-world>

或者我在这里遗漏了什么?使用require属性指定控制器也是可取的。

答案 2 :(得分:0)

在没有范围的指令中,只需在指令模板中访问mycontroller.callback()

.directive('helloWorld', function () {
    return {
        restrict: 'E',
        scope: false,
        //Use THIS
        template: '<button ng-click="mycontroller.callback()">Not isolated</button>',
        //NOT this                  
        //template: '<button ng-click="callback()">Not isolated</button>',
        controller: function ($attrs, $scope, $parse) {
              //$scope.callback = $parse($attrs.callback)($scope);
        }
    }
});

由于directice没有自己的范围,因此模板可以直接访问使用ng-controller="MyCtrl as mycontroller"实例化的控制器。

  

如果你想重用指令怎么办?

在这种情况下,将单击处理程序绑定到元素。

.directive('helloWorld', function () {
    return {
        restrict: 'E',
        scope: false,
        template: '<button>Not isolated</button>',
        link: function (scope, elem, attrs) {
             elem.on("click", function(e) {
                 scope.$eval(attrs.callback, {$event: e});
             });
        }
    }
});

当单击指令的元素时,callback属性定义的Angular表达式将使用公开为$event的事件对象进行评估。

有关$event的详细信息,请参阅AngularJS Developer Guide -- $event

相关问题