简体   繁体   中英

Evaluating expression in ng-controller

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.com/ubevel/13/edit )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM