我有这个控制器:
.controller('UserListEditorController', function ($scope) {
$scope.status = {
isopenFields: false,
isopenFilters: false
};
$scope.toggleDropdownFields = function($event) {
$scope.status.isopenFields = !$scope.status.isopenFields;
};
$scope.toggleDropdownFilters = function($event) {
$scope.status.isopenFilters = !$scope.status.isopenFilters;
};
})
我有这个指令:
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
element.on('mousedown', function(event) {
element.data('mousedown', true);
});
element.on('focusin', function(event) {
if (element.data('mousedown')) {
Calling $scope.toggleDropdown
}
});
}
};
}]);
如何从自定义指令调用控制器$ scope中的函数?
答案 0 :(得分:3)
您已创建指令类型shared scope
,因此如果您定义具有共享范围的指令,则可以直接访问ng-controller
就像,
scope.sayHello();
这是DEMO
您可能在调用element.data..
时出错了,在angular指令中,您可以访问您放置到元素的属性attr.mousedown
这是一个很好的Series to Refer
答案 1 :(得分:0)
如果指令范围未隔离且指令在控制器scope.toggleDropdownFields()
范围内调用,则可以使用UserListEditorController
。
请参阅
HTML
<button ng-controller="MyCtrl" dir>I just met you</button>
角
var app = angular.module('plunker', []);
app.directive('dir', function ($parse) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
element.bind('click', function (e) {
scope.click();
});
}
};
});
app.controller('MyCtrl',function($scope) {
$scope.click = function () {
console.log("Whatever you want to do");
};
});
答案 2 :(得分:0)
这是一种方法:
标记:
<button ng-controller="SomeCtrl" my-directive call-me="callMeMaybe()">I just met you</button>
JS:
var app = angular.module('myApp', []);
app.directive('myDirective', function ($parse) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attrs) {
element.bind('click', function (e) {
scope.$apply(attrs.callMe);
});
}
};
});
function SomeCtrl($scope) {
$scope.callMeMaybe = function () {
alert('I just called you, maybe');
};
}