【发布时间】:2016-08-05 20:28:12
【问题描述】:
我有一个类似这样的指令:
app.directive('example', function() {
return {
restrict: 'E',
transclude: true,
scope: {
callback: '&'
},
template: '<span ng-click="example.callback()">Click Me</span>',
bindToController: true,
controllerAs: 'example',
controller: function() {
this.counter = 0;
this.incrementCount = function() {
this.counter++;
};
this.getCount = function() {
return this.counter;
};
},
link: function(scope, el, attrs, ctrl) {
var oldCallback = scope.callback;
ctrl.callback = function() {
console.log(ctrl);
return oldCallback.call(ctrl); // I want to be able to use `this` as the controller to access the API from within the callback
};
}
};
});
使用控制器
app.controller("ctrl", ["$scope", function(s) {
s.callback = function() {
this.incrementCount();
console.log("Value: " + this.getCount());
};
}]);
然后查看
<div ng-app="app">
<div class="container" ng-controller="ctrl">
<example callback="callback()"></example>
</div>
</div>
当我在链接函数的 ctrl.callback 中登录 ctrl 时,它会按我的预期记录示例控制器,但是当调用 oldCallback 时,它不会按我的意愿将 ctrl 反弹到 this。有什么方法可以从作用域的回调中访问指令控制器中定义的 API,同时仍然为指令使用隔离作用域?
【问题讨论】:
-
为什么要使用链接功能?您应该能够将 $scope 传递到控制器并从那里访问 $scope.callback。
-
在实际指令中,我使用链接来装饰回调以返回 true,除非它出于流量控制的目的显式返回 false。
标签: angularjs angularjs-directive