如果我想分配动态 Controller ,我可以执行以下操作:
<div ng-controller="MainController">
<div ng-controller="dynamicController"></div>
</div>
function MainController($scope){
$scope.dynamicController = MyCtrl;
$scope.instanceName = "ctrl"; // we'll use this later
}
function MyCtrl(){}
我该怎么做才能使其使用新的“controller as”语法?
这工作正常:<div ng-controller="dynamicController as ctrl"></div>
但是如何制作ctrl
也动态?假设我希望它的名称为 $scope.instanceName
成立。
fiddle :http://jsfiddle.net/ftza67or/2/
有一个想法可以创建一个自定义指令来创建和编译 html 字符串,但这是一种丑陋的方式,让我们假装它不存在。
最佳答案
这应该工作得几乎相同,但请记住,当您使用 controller as
时,您可以将属性绑定(bind)到 Controller 内的 this
以让范围访问它们/查看。
function MainController ($scope) {
$scope.dynamicController = MyCtrl;
}
function MyCtrl($scope) {
this.foo = "baz";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="MainController">
<div ng-controller="dynamicController as ctrl">
{{ctrl.foo}}
</div>
</div>
关于javascript - 具有 "controller as"语法的动态 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671739/