2016-11-03 10 views
0

カスタムTypeScriptディレクティブでコントローラのスコーププロパティにアクセスするにはどうすればよいですか?
例えば、私はscope.messageを記録したい次のスニペットで:アクセススコープfrom directives with typescript

/// <reference path="typings/angularjs/angular.d.ts" /> 

//module 
module app { 
    var mainModule = angular.module('mainModule', []); 
} 

//controller 
module app.testCtrl { 
    interface ITest { 
     message: string; 
    } 

    class TestCtrl implements ITest { 
     message: string = 'initial value'; // this is the value i want to access from my dierctive 
    } 
    angular.module('mainModule').controller('testCtrl', TestCtrl); 
} 

//directive 
module app.directives { 
    export class MyDirective implements ng.IDirective { 
     restrict = 'A'; 

     static instance(): ng.IDirective { 
      return new MyDirective; 
     } 

     link(scope: ng.IScope) { 
      //HOW DO I GET TO THE SCOPE PROPERTIES? 
      //console.log(scope.???); 
     } 

    } 
    angular.module('mainModule').directive('myDirective', MyDirective.instance); 
} 

PS - それは違いを作る場合、あなたがしているように私は、ビューの構文「のようなコントローラを」使用してい

+0

説明してください**あなたがそれをしたい理由は、あなたがそれを悪用しているようです。あなたは 'console.log(scope.myControllerAsAlias.message);を実行することができます。しかし、「角度のある方法」は、コントローラから読み出す代わりにプロパティをディレクティブに渡すことです。 – devqon

答えて

0

はそう角度の指示の概念を悪用している。 、

link(scope: ng.IScope) { 
    console.log(scope["myControllerAsAlias"].message); 
} 

しかし、「角度の方法は」ディレクティブに変数を渡すことであろう。このような何か:あなたはこのような何かを行う場合は、コントローラのスコープ変数にアクセスすることができます

interface IMyDirectiveScope extends ng.IScope { 
    message: string 
} 

export class MyDirective implements ng.IDirective { 
    restrict = 'A'; 
    scope = { 
     message: "@" 
    }; 

    static instance(): ng.IDirective { 
     return new MyDirective; 
    } 

    link(scope: IMyDirectiveScope) { 
     console.log(scope.message); 
    } 

} 

をとあなたのhtmlで:

<div my-directive message="myCtrlAsAlias.message"></div> 
+0

'scope.vm.message'は「プロパティが存在しないというエラー」を返します。 'scope ['vm']。message'が動作します。質問はどのように入力(2番目の提案)を入力に使用するのですか?あるいは代わりに 'ngModel'をターゲットにする必要がありますか?それを実装することはできません... – Yoav

+0

あなたの目標を正確に説明してください。この回答はあなたの質問に答えましたが、あなたが本当に達成したいと思っていることのほんの一部を聞いたようです – devqon

関連する問題