Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 245
Michael Allan Jackson Avatar asked Feb 26 '13 07:02

Michael Allan Jackson


1 Answers

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/

like image 78
Michelle Tilley Avatar answered Nov 02 '22 03:11

Michelle Tilley