Как вы вызываете функцию директивы из контроллера?
Я видел несколько ответов на этот вопрос, решение которых похоже на следующее:
https://lennilobel.wordpress.com/tag/calling-directive-from-controller/
Я реализовал это следующим образом:
Директива
angular.module('myApp').directive('myDirective', ['$log',
function ($log) {
function link(scope, element, attributes) {
//function that a controller can call
scope.myFunc = function () {
//Do Something
};
//if the user has provided an accessor, attach the function
if (scope.accessor) {
scope.accessor.myFunc = scope.myFunc;
}
}
return {
link: link,
restrict: 'E',
templateUrl: 'app/myTemplate.html',
scope: {
accessor: '=',
}
}
}
Контроллер
angular.module('myApp').controller('myCtrl', ['$log', '$q',
function ($log, $q) {
var vm = this;
// empty object that the directive will attach myFunc to
vm.accessor = {};
$q
.all([
//Service Call
])
.then(function (results) {
//manipulate the results of the service call using the
//directives function
vm.callDirective();
},
function (err) {
$log.debug('$q.all err:', err);
});
vm.callDirective = function () {
if (vm.accessor.myFunc) {
vm.accessor.myFunc();
} else {
$log.error('umm, I don\'t have a function to call');
}
};
}
HTML-шаблон
<div ng-controller="myCtrl">
<myDirective accessor="vm.accessor"></myDirective>
</div>
Когда я запускаю код, директива указывает, что accessor не определен. В результате, accessor в контроллере не определил myFunc .
Как мне заставить myFunc выполнить?
Я использую угловой 1.7.2