引用下面的示例,有没有办法使用 myCtrl 而不是 myCtrl2,将参数作为本地参数传递而不是附加到 $scope?
$controller服务完全执行包装现有 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;
}
最佳答案
我不能完全从你的问题中告诉你到底在找什么,但你可以尝试创建你自己的指令(the ngController
directive 的修改版本)可以指定 Controller 注入(inject):
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);
}
};
});
你会像这样使用它:
<div my-controller='MainController' locals='{x: "test", y: 42}'></div>
这是一个演示该技术的 JsFiddle:http://jsfiddle.net/BinaryMuse/qBZZk/
关于javascript - 可以将本地人注入(inject)到带有 ng-controller 的 Controller 集中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15083675/