JavaScript函数:
var API = (function(){
return {
function invokeDirective(){
invvoke();
$scope.setItem() // to directive
}
}
});
指令:
angular.module('sampleComponents', ['$strap.directives']).directive('titlebar',
function($filter,$timeout)
{
return {
restrict: 'AE',
replace: true,
scope: true,
transclude: true,
template: '<div class="searchBar r etc ........',
controller: function($scope,$http,$timeout)
{
$scope.setItem = function(){
// want to invoke this function from api.js -
}
}
link: function(scope, element, attrs){
// etc:
}
});
如何从$scope.setItem
调用api.js
?可能吗?请建议。
(目前,我正在使用计时器,但这会产生一些性能问题)
答案 0 :(得分:1)
是的,你可以用非常黑客的方式做到这一点。
演示代码:
//This is too get scope outside of angular controller/service/directive
//with a hacky way to do that.
var $injector =angular.injector(['ng','MyApp']);
var html = "<div titlebar=''></div>";
$injector.invoke(function($compile, $rootScope){
var $scope = $rootScope.$new();
var result= $compile(html)($scope);
var cScope = result.scope(); // This is scope in directive controller. : )
//Do anything you want with this scope .
});
快乐的编码。 :)