Can local people be entered into a controller installed using an ng controller?

Referring to the example below, is there a way to use myCtrl instead of myCtrl2 by passing the argument as local rather than attached to $ scope?

The $ controller service performs exactly the operation that is necessary to wrap an existing controller, but it cannot be accessed from the template.

<div ng-app> <script type="text/ng-template" id="/tpl.html"> value of y: {{y}} </script> <div ng-repeat='x in [1,2,3]' ng-controller='myCtrl2' ng-include="'/tpl.html'"> </div> </div> 
 function myCtrl($scope, x){ $scope.y = x * 20; } function myCtrl2($scope){ $scope.y = $scope.x * 20; } 

http://jsfiddle.net/4Zmym/16/

+4
source share
1 answer

I can’t say from your question what you are really looking for, but you can try to create your own directive (a modified version of the ngController directive ) may indicate injections for the controller:

 app.directive('myController', function($controller) { return { scope: true, link: function(scope, elem, attrs) { var locals = scope.$eval(attrs.locals); angular.extend(locals, {$scope: scope}); $controller(attrs.myController, locals); } }; }); 

You would use it something like this:

 <div my-controller='MainController' locals='{x: "test", y: 42}'></div> 

Here's a JsFiddle demonstrating the technique: http://jsfiddle.net/BinaryMuse/qBZZk/

+12
source

All Articles