如何从 JavaScript 调用指令函数

how to Invoke directive function from javascript

本文关键字:指令 函数 调用 JavaScript      更新时间:2023-09-26

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:
        }
});

如何从api.js调用$scope.setItem?可能吗?请指教。

(目前,我正在使用计时器,但这会产生一些性能问题)

是的,你可以用一种非常笨拙的方式做到这一点。

演示代码:

//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 .
});

这是Jsfiddle。

快乐编码。