문제

AngularJS directives specify a controller using:

{
  controller: function ($scope){}
}

As of yet, I have not found a way where I can create a TypeScript class and assign it to a directive's controller property.

What I would like to do is something like

interface IDirectiveController{
    myProperty:string;
}

class DirectiveController implements IDirectiveController{
   static $injector = [$scope];
   constructor ($scope:ng.IScope){
       this.myProperty = 'default';
   }

   public myProperty:string;
}


var directive:ng.IDirective =
{
   controller:DirectiveController;
}
return directive;

Better yet, it would be nice if a factory function could be used that would let me create and return a new instance of the controller, similar to how the directive itself is instantiated.

In my directive template I would also like to bind directly to the controller rather than having to assign the properties of the class to $scope.

Another way of stating this might be to say, I would like to be able to assign controllers to directives in a manner similar to assigning a controller using the myController as ContollerType syntax that is available in a template.

도움이 되었습니까?

해결책

I believe you could do something like this in your directive:

...
controller: DirectiveController,
controllerAs: 'myCtrl'
...

Then angular should instantiate your class with its constructor and you can refer to it in the template with myCtrl

다른 팁

Simply do what you would do in the absence of a directive i.e. :

class DirectiveController{
   static $inject = ['$scope']; // fixed a few typos here
   constructor ($scope){
       $scope.vm = this;        // this is the pattern I recommend for all controllers
       this.myProperty = 'default';
   }

   public myProperty:string;
}

To learn more about this pattern see : http://www.youtube.com/watch?v=WdtVn_8K17E&hd=1

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top