My 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 ?
JSBIn Link()
My 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 ?
JSBIn Link(http://jsbin./ubevel/13/edit)
Share Improve this question asked Oct 26, 2013 at 9:46 AbhikAbhik 1,9407 gold badges27 silver badges50 bronze badges 1- what is use case for needing to do this? Likely other ways to acplish needs – charlietfl Commented Oct 26, 2013 at 13:49
2 Answers
Reset to default 6Write controller as function (not as app.controller('Test'
)
Change JS to:
var app = angular.module('Demo', []);
app.controller('DemoCtrl', function ($scope) {
$scope.expr = Test;
});
function Test($scope) {
$scope.HELLO = "HEllo World";
}
And HTML:
<body ng-controller="DemoCtrl">
<div ng-controller="expr">{{HELLO}}</div>
</body>
Demo JS BIn
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.