Can locals be injected into a controller set with ng-controller?

All we need is an easy explanation of the problem, so here it is.

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

The $controller service performs exactly the operation needed to wrap an existing controller, but it can’t 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/

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I can’t quite tell from your question what exatly you’re looking for, but you might try creating your own directive (a modified version of the ngController directive) can specify controller injectables:

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 that demonstrates the technique: http://jsfiddle.net/BinaryMuse/qBZZk/

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply