[英]Evaluating expression in ng-controller
My Javascript 我的Javascript
var app = angular.module('Demo', []);
app.controller('DemoCtrl', function ($scope) {
$scope.expr = "Test"
});
app.controller('Test', function ($scope) {
$scope.HELLO = "HEllo World";
});
My Mark Up 我的马克
<body ng-controller="DemoCtrl">
<div ng-controller="{{expr}}">{{HELLO}}</div>
</body>
This does not work.The documentation says that ng-controller can evaluate expressions.What am I doing wrong ? 这不起作用。文档说ng-controller可以评估表达式。我做错了什么?
JSBIn Link ( http://jsbin.com/ubevel/13/edit ) JSBIn Link ( http://jsbin.com/ubevel/13/edit )
Write controller as function (not as app.controller('Test'
) 将控制器写为函数(而不是app.controller('Test'
)
Change JS to: 将JS更改为:
var app = angular.module('Demo', []);
app.controller('DemoCtrl', function ($scope) {
$scope.expr = Test;
});
function Test($scope) {
$scope.HELLO = "HEllo World";
}
And HTML: 和HTML:
<body ng-controller="DemoCtrl">
<div ng-controller="expr">{{HELLO}}</div>
</body>
That is the expected behaviour and a clearer reading of the docs further clarifies it: 这是预期的行为,更清楚地阅读文档进一步澄清了它:
Name of a globally accessible constructor function or an expression that on the current scope evaluates to a constructor function. 全局可访问的构造函数的名称或当前作用域上的表达式求值为构造函数。
Hence, one can either use a string, or one can use an expression which returns a constructor for the controller, but not an expression which returns a string which is the name of the controller. 因此,可以使用字符串,也可以使用返回控制器构造函数的表达式,但不能返回返回字符串的表达式,该字符串是控制器的名称。
As to how to make it work, Maxim has already largely answered your question: by making the expression
return a constructor for the controller. 至于如何使它工作,Maxim已经在很大程度上回答了你的问题:通过使expression
返回控制器的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.