最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Evaluating expression in ng-controller - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

Write 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.