2016-10-06 6 views
0

지시문에서 컨트롤러 기능을 호출하려고하는데 "this"컨텍스트 문제가 발생합니다. 함수가 지시문을 통해 호출되면 logSerivce에 액세스 할 수 없습니다. 여기via 유형 스크립트를 통해 Angularjs 컨트롤러가 지시문에서 컨트롤러 기능을 호출합니다.

컨트롤러 클래스 : 여기

class MainController implements IMainScope { 

     static $inject = ["LogService"]; 

     constructor(private logService:ILogService) { } 

     sayHello(message:string) { 
      console.log("MainController sayHello", message); 
      // Cannot read property 'logService' of undefined if gets call from directive 
      this.logService.log(message); 
     } 
    } 

지시어 클래스 : http://embed.plnkr.co/Ov7crFZkkjDPzilX2BmL/

답변

0

당신이 testFn를 호출하는 방법 : 여기

class TestDirective implements ng.IDirective { 
     public restrict = "E"; 
     public templateUrl = "test-directive.html"; 
     public replace = true; 
     public scope:any = { 
      testFn: "&" 
     }; 

     constructor() { } 

     public link:ng.IDirectiveLinkFn = (scope:TestDirectiveScope, element:ng.IAugmentedJQuery, attrs:ng.IAttributes):void => { 
      scope.hello =() => { 
       console.log("TestDirective", scope.firstName); 
       scope.testFn()(scope.firstName); 
      }; 
     } 

     static factory():ng.IDirectiveFactory { 
      let directive:ng.IDirectiveFactory =() => new TestDirective(); 
      return directive; 
     } 
    } 

내 문제를 다루고 간단한 plunker의 예입니다 지시어에서 올바른 방법이 아닙니다. 함수를 호출하여 데이터를 전달하려면 먼저

ng-click="vm.sayHello(message)" 

을 사용하고 지침에서 함수를 호출하면서 괄호 안의 {message: 'some value'} 같은 JSON/객체 형식으로 전달합니다. 콜백으로 전달 해야하는

scope.testFn({message: scope.firstName}); 

Demo Plunkr

+0

고마워요! 그것은 작동! 유감 스럽지만 데모 링크에는 업데이트 버전이 표시되지 않습니다. 나는이 호출을 변경했다 :'test-directive test- fn = "vm.sayHello (message)"'와 지시문의 호출. 'scope.testFn ({message : scope.firstName});'[여기에 새로운 데모 버전이 있습니다.] (https://embed.plnkr.co/nd54cRZqMDtnVM4XXhog/). 다시 한번 고마워! – stevo

+0

@stevo 완전히 업데이트하는 걸 잊었습니다.) 감사합니다 –

+0

첫 번째 코드를'fn = "vm.sayHello (message)'로 업데이트하고 싶을 수도 있습니다. – stevo

0

방법은 (각도가이 범주에 바인딩) 그 문맥에 바인드해야합니다. TypeScript의 경우 화살표 함수로 메소드를 정의하는 데 바람직한 방법은 다음과 같습니다.

sayHello = (message:string) => { ... } 
관련 문제