问题描述
请参见下面的示例,是否有一种方法可以使用myCtrl而不是myCtrl2,将参数作为局部变量传递,而不是附加到$ scope?
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?
$ controller 服务完全执行包装现有控制器所需的操作,但无法从模板访问它.
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;
}
推荐答案
我不能退出从问题中得知您要查找的内容,但是您可以尝试创建自己的指令( ngController
指令的修改版本可以指定控制器注射剂:
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>
这里是一个演示该技术的JsFiddle: http://jsfiddle.net/BinaryMuse/qBZZk/
Here's a JsFiddle that demonstrates the technique: http://jsfiddle.net/BinaryMuse/qBZZk/
这篇关于可以将本地人注入到使用ng-controller设置的控制器中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!