最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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;
}

/

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/4Zmym/16/

Share Improve this question edited Feb 26, 2013 at 10:00 M J asked Feb 26, 2013 at 7:30 M JM J 4,3273 gold badges37 silver badges46 bronze badges 6
  • Could you please clarify a bit what you are trying to achieve? the question is a bit chatty/theoretical.. – George Katsanos Commented Feb 26, 2013 at 7:43
  • Ok, I'll start deleting... – M J Commented Feb 26, 2013 at 7:45
  • The description is good, but I couldn't find the "question" part anywhere:) – George Katsanos Commented Feb 26, 2013 at 7:47
  • One thing's for sure, You cannot inject locals with ng-controller. – George Katsanos Commented Feb 26, 2013 at 7:55
  • The $controller service does exactly what I want, but not from the template...I was just wondering if there was a trick to pull it off simply. – M J Commented Feb 26, 2013 at 8:01
 |  Show 1 more ment

1 Answer 1

Reset to default 13

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/BinaryMuse/qBZZk/

发布评论

评论列表(0)

  1. 暂无评论