2014-11-26 3 views
2

에서 지시 함수를 호출하는 자바 스크립트 기능 :방법 자바 스크립트

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를 호출 할 수 있습니다? 가능한가? 제발 제안 해주세요.

+5

API.js 자체가 의존 서비스로 지시문에 삽입 된 각도 서비스 여야합니다. 그런 다음 필요한 경우 외부 API를 통해 서비스 호출을 노출해야합니다. – CodingIntrigue

답변

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

This is Jsfiddle.

해피 코딩. :)