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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With