为什么我的角度代码不起作用?

时间:2015-11-17 13:42:18

标签: javascript angularjs

嘿,我是棱角分明的新人,我无法让它发挥作用 我做了一个新项目,我把angular.min.js文件放到这个代码不起作用,我不知道为什么它什么也没显示 请帮我理解原因。

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

app.controller('peopleListCtrl', function(){
  this.persons = plists;
});

var plists = [
             { name: 'alon', job: 'web dev', home:'nir tzvi' },
{ name: 'ben', job: 'katbamflighter', home:'nir tzvi' },
{ name: 'shiraz', job: 'dentist assistant', home:'hadera west' }
];
})();
<!DOCTYPE html>
<html ng-app="list">
<head>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="peopleListCtrl as ppl">
<br />
<div ng-repeat="people in ppl.persons">
<h3>
 {{people.name}}
{{people.job}}
{{people.home}}
</h3>
  </div>
    <input type="text" />
<br />
</body>
  </html>

4 个答案:

答案 0 :(得分:3)

请参阅此说明$scope vs this in AngularJS controller

查看工作代码。

&#13;
&#13;
(function() {
  var app = angular.module('list', []);

app.controller('peopleListCtrl', ['$scope',function($scope){
  $scope.persons = plists;
}]);

var plists = [
             { name: 'alon', job: 'web dev', home:'nir tzvi' },
{ name: 'ben', job: 'katbamflighter', home:'nir tzvi' },
{ name: 'shiraz', job: 'dentist assistant', home:'hadera west' }
];
})();
&#13;
<!DOCTYPE html>
<html ng-app="list">
<head>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="peopleListCtrl">
<br />
<div ng-repeat="people in persons">
<h3>
 {{people.name}}
{{people.job}}
{{people.home}}
</h3>
  </div>
    <input type="text" />
<br />
</body>
  </html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

除了上面的答案,如果你真的想使用controller as语法来使用属于控制器对象的方法和变量而不是经典$scope注入,你需要使用更现代版的AngularJS恐怕。

以下是使用AngularJS v1.4.7的代码:http://plnkr.co/edit/FIrK0o8493k3VjDBSNtM?p=preview

希望它增加一些澄清!

答案 2 :(得分:0)

尝试用控制器中的$ scope.persons替换this.persons,$ scope将确保您可以使用模板中的数据。

app.controller('peopleListCtrl',['$scope', function($scope){
  $scope.persons = plists;
});

答案 3 :(得分:0)

您的ng-controller应该只是peopleListCtrl而不是peopleListCtrl as ppl

您还需要将控制器中的this.persons更改为$scope.persons

然后将HTML更改为:

<!DOCTYPE html>
<html ng-app="list">
<head>
 <script type="text/javascript"     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js">    </script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="peopleListCtrl as ppl">
<br />
<div ng-repeat="people in persons">
<h3>
 {{people.name}}
{{people.job}}
{{people.home}}
</h3>
  </div>
   <input type="text" />