简体   繁体   English

angular不会渲染$ scope

[英]angular doesn't render $scope

I try to display some variable of my controller, but the output is just {{UserCtrl.user}} instead of the content of UserCtrl.user . 我尝试显示我的控制器的一些变量,但输出只是{{UserCtrl.user}}而不是UserCtrl.user的内容。

I got the following file structure: 我有以下文件结构:

  • index.html
  • scripts/app.js

This is the code of index.html : 这是index.html的代码:

<!doctype html>
<html lang="en" ng-app="birdsnest">
<head>
    <meta charset="utf-8">

    <title>Birdsnest</title>

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.css">
</head>
<body>
    <div ng-controller="UserController as UserCtrl">
        {{UserCtrl.user}}
    </div>

    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script src="bower_components/angular/angular.js"></script>

    <script src="scripts/app.js"></script>
</body>
</html>

scripts/app.js : scripts/app.js

(function() {
  var app = angular.module('birdsnest', []);

  app.controller('UserController', ['scope', function($scope) {
    $scope.user = 'Michael';
  }]);
})();

Change this line: 改变这一行:

app.controller('UserController', ['scope', function($scope) {

To: 至:

 app.controller('UserController', ['$scope', function($scope) {

Edit: If you're using controllerAs then I think you should rewrite your code: 编辑:如果您正在使用controllerAs那么我认为您应该重写您的代码:

app.controller('UserController', function() {
  this.user = 'Michael';
}); 

When you're using the ControllerAs syntax in your HTML, the values that end up getting bound to the controller instance is actually on your this object. 当您在HTML中使用ControllerAs语法时,最终绑定到控制器实例的值实际上在您的this对象上。

What this means is that your code that attaches user to the scope object is incorrect; 这意味着将user附加到scope对象的代码不正确; instead you should do the following: 相反,你应该做以下事情:

app.controller("UserController", function() {
  this.user = "Michael";
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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