2016-09-09 10 views
0

指示文でコントローラを必要としたいのですが、コントローラが見つからないというエラーが表示されます。私はそれが小さなことであると確信している、または多分それは私がそれをやりたい方法が可能ではありません。コントローラから指示にアクセスする必要があります

angular.module('myApp', []); 
 

 
angular.module('myApp').controller('GreetingController', ['$scope', function($scope) { 
 
    $scope.greeting = 'Hola!'; 
 
    
 
    //some function here returning data 
 
}]); 
 

 
angular.module('myApp').directive('yoloswag', function() { 
 
    return { 
 
    require: ['^?ngModel', '^GreetingController'], 
 
    restrict: 'A', 
 
    scope: { 
 
    }, 
 
    link: function(scope, element, attrs, controllers) { 
 
     
 
     var modelCtrl = controllers[0], 
 
      greetingsCtrl = controllers[1]; 
 
     
 
     console.log(controllers) 
 
    } 
 
    }; 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
 
<div ng-app="myApp"> 
 
    <div ng-controller="GreetingController"> 
 
    {{ greeting }} 
 
    <div yoloswag>test</div> 
 
</div> 
 
    
 
</div>

私が間違って何をしているのですか?

ありがとうございました!

答えて

0

あなたのコードはメインモジュールに依存しないため、そのエラーが発生しています。

あなたのコードは、あなたのようなメインモジュールとコントローラとディレクティブを追加することができます

angular.module('myApp', []) 
.controller('GreetingController', ['$scope', function($scope) { 
    $scope.greeting = 'Hola!'; 

    //some function here returning data 
}]) 
.directive('yoloswag', function() { 
    return { 
    require: ['^?ngModel', '^GreetingController'], 
    restrict: 'A', 
    scope: { 
    }, 
    link: function(scope, element, attrs, controllers) { 

     var modelCtrl = controllers[0], 
      greetingsCtrl = controllers[1]; 

     console.log(controllers) 
    } 
    }; 
}); 

またはメインモジュールのための変数を設定し、次のする必要があり、

var MainModule = angular.module('myApp', []); 

    MainModule.controller('GreetingController', ['$scope', function($scope) { 
     $scope.greeting = 'Hola!'; 

     //some function here returning data 
    }]); 
    MainModule.directive('yoloswag', function() { 
     return { 
     require: ['^?ngModel', '^GreetingController'], 
     restrict: 'A', 
     scope: { 
     }, 
     link: function(scope, element, attrs, controllers) { 

      var modelCtrl = controllers[0], 
       greetingsCtrl = controllers[1]; 

      console.log(controllers) 
     } 
     }; 
    }); 
+0

こんにちはRamesh R、あなたの反応に感謝します。コードを変更した後も、エラーは同じです。 http://codepen.io/anon/pen/dpYyjV?editors=1111 – fomm

+0

jsファイルをHTMLファイルに参照(インポート)しましたか? –

0

あなたがのcontrollerプロパティを使用することができます指示:

リンク機能でプロパティを更新しないでください。

return { 
    restrict: 'A', 
    scope: { 
    }, 
    controller : 'GreetingController', 
    link: function(scope, element, attrs) { 

     var modelCtrl = controllers[0], 
      greetingsCtrl = controllers[1]; 

     console.log(controllers) 
    } 
    }; 
関連する問題