2016-12-21 2 views
0

Bitte schauen Sie auf den folgenden Code:AngularJS: Warum funktioniert nicht ng-repeat?

<html lang="en" > 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
    <script src="app.js"></script> 
    </head> 

<body ng-app="flexbox" > 

    <div id="wrapper" ng-controller="flex-ctrl as ctrl"> 
     <div id="aside"> 
     <p ng-repeat="item in ctrl.buttons"> {{item}} </p> 
     </div> 
    </div> 
</body> 
</html> 


var app = angular.module("flexbox", []); 
app.controller("flex-ctrl", ['$scope', function($scope) { 
    $scope.buttons = ['a','b', 'c']; 
}]); 

Ich erwarte, dass drei <p> Artikel zu sehen. Es sieht jedoch so aus, als ob ng-repeat ignoriert wird und ich eine leere Seite sehe.

Weißt du, was das Problem ist?

Für Ihre Bequemlichkeit: http://codepen.io/CrazySynthax/pen/yVwWdo

+1

nur Strg entfernen –

Antwort

1

Ihre Variable ist in $scope, so können Sie einfach Schleife über es mit:

<p ng-repeat="item in buttons"> {{item}} </p> 

Statt

<p ng-repeat="item in ctrl.buttons"> {{item}} </p> 

Forked your Codepen here.

2

Verwenden this.buttons statt $ scope.buttons da Sie verwenden controller as Syntax

var app = angular.module("flexbox", []); 
 
app.controller("flex-ctrl", ['$scope', function($scope) { 
 
    this.buttons = ['a','b', 'c']; 
 
}]);
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <script data-require="[email protected]" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script> 
 
</head> 
 
<body ng-app='flexbox'> 
 
    <div id="wrapper" ng-controller="flex-ctrl as ctrl"> 
 
     <div id="aside"> 
 
     <p ng-repeat="item in ctrl.buttons"> {{item}} </p> 
 
     </div> 
 
    </div> 
 
</body> 
 
</html>

2

Da Sie Controller als Syntax verwenden Sie Ihre Abfrage wie so ändern können:

var app = angular.module("flexbox", []); 

app.controller("flex-ctrl", [function() { 
    var vm = this; 
    vm.buttons = ['a','b', 'c']; 
}]); 

hoffe es hilft.

Verwandte Themen