[英]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? 参考下面的例子,有没有办法使用myCtrl而不是myCtrl2,将参数作为本地传递而不是附加到$ scope?
The $controller service performs exactly the operation needed to wrap an existing controller, but it can't be accessed from the template. $ controller服务完全执行包装现有控制器所需的操作,但无法从模板访问它。
<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;
}
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: 我不能完全从你的问题中看出你正在寻找什么,但你可能会尝试创建自己的指令( ngController
指令的修改版本)可以指定控制器注入:
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/ 这是一个演示技术的JsFiddle: http : //jsfiddle.net/BinaryMuse/qBZZk/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.