“控制器为”不使用ng-repeat

时间:2017-07-18 02:05:45

标签: javascript angularjs angularjs-scope

我正在尝试在“Controller as”块中填充列表,但我似乎无法显示任何内容。我已经得到了一个与$scope合作的最小例子:

JS:

var app = angular.module('testApp', []);
app.controller('listController', ["$scope", ($scope) => {
  $scope.listFiles = ["hello", "world"];
}]);

HTML:

<div ng-app="testApp" ng-controller="listController">
  <div class="list-group">
    <a class="list-group-item list-group-item-action" ng-repeat="filename in listFiles">{{ filename }}</a>
  </div>
</div>

JSFiddle

但是当我介绍“Controller as”时,列表不会显示:

JS:

var app = angular.module('testApp', []);

app.controller('listController', ["$scope", ($scope) => {
  var $ctrl = this;
  $ctrl.listFiles = ["hello", "world"];
}]);

HTML:

<div ng-app="testApp" ng-controller="listController as ctrl">
  <div class="list-group">
    <a class="list-group-item list-group-item-action" ng-repeat="filename in ctrl.listFiles">{{ filename }}</a>
  </div>
</div>

JSFiddle

我理解$scopethis是不同的概念,但在这种情况下我似乎无法理解具体细节。

这可能是ng-repeat的范围规则的结果,还是我错过了一些明显的东西?

2 个答案:

答案 0 :(得分:2)

在定义arrow function时,您不应使用controller function,这会导致this出现不属于控制器本身的意外情境。解决方案是使用普通function

参考以下示例并修复 jsfiddle

var app = angular.module('testApp', []);

app.controller('listController', ["$scope", function($scope) {
  var $ctrl = this;
  this.listFiles = ["hello", "world"];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="testApp" ng-controller="listController as ctrl">
  <div class="list-group">
    <a class="list-group-item list-group-item-action" ng-repeat="filename in ctrl.listFiles">{{ filename }}</a>
  </div>
</div>

答案 1 :(得分:1)

您使用过es6箭头函数语法。由于浏览器不支持es6语法。您必须使用transpiler(Babel)将es6代码编译为纯javascript。

尝试更改此

'use strict'

function Animal (name) {
    this.name = name
}

// Animal.prototype.walk = (destination) => {
//     console.log(this.name + " walk to " + destination)  //undefined walk to China
// }

Animal.prototype.walk = function (destination) {
    console.log(this.name + " walk to " + destination)  //Cat walk to China
}

const cat = new Animal("Cat")
cat.walk('China')

I want to know the reason, thanks!

使用

app.controller('listController', ["$scope", ($scope) => {

JSFiddle