Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在AngularJS的ng repeat中使用控制器中的变量_Javascript_Angularjs - Fatal编程技术网

Javascript 如何在AngularJS的ng repeat中使用控制器中的变量

Javascript 如何在AngularJS的ng repeat中使用控制器中的变量,javascript,angularjs,Javascript,Angularjs,我只是在学习AngularJS,并希望在ng中使用来自控制器的repeat变量(不使用范围),但它不起作用。有人能指出我的错误吗?这是我的代码: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <div ng-app="myApp"

我只是在学习AngularJS,并希望在ng中使用来自控制器的repeat变量(不使用范围),但它不起作用。有人能指出我的错误吗?这是我的代码:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<select>
    <option ng-repeat="x in myCtrl.names">{{x}}</option>
</select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    var that = this;
    that.names = ["Emil", "Tobias", "Linus"];
});
</script>
</body>
</html>

{{x}
var-app=angular.module('myApp',[]);
应用程序控制器('myCtrl',函数($scope){
var=这个;
that.names=[“Emil”、“Tobias”、“Linus”];
});

在作用域上设置变量。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.names = ["Emil", "Tobias", "Linus"];
});
在控制器中使用变量

var-app=angular.module('myApp',[]);
app.controller('myCtrl',function(){
var self=这个;
self.names=[“Emil”、“Tobias”、“Linus”];
});

{{x}

不要使用直接控制器名称,而是使用我们提到的控制器名称在html代码中使用“as”关键字声明的名称

例如:

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
    var viewData = this;
    viewData.names = ["Emil", "Tobias", "Linus"];
});

<div ng-app="myApp" ng-controller="myCtrl as Ctrl">
    <select>
        <option ng-repeat="x in Ctrl.names">{{x}}</option>
    </select>
</div>
var-app=angular.module('myApp',[]);
app.controller('myCtrl',function(){
var viewData=this;
viewData.names=[“Emil”、“Tobias”、“Linus”];
});
{{x}

我不想使用作用域。@iJava我已经更新了答案,包含了一个没有作用域的解决方案。您好,您能解释一下它是如何不起作用的吗?你是有错误,还是只是失败了?@ChrisAlexander,它根本不起作用。您可以尝试运行代码。