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
1 Answer
Reset to default 13I 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/