如何在不使用$ scope时刷新ng-repeat列表?

时间:2017-03-29 10:34:34

标签: angularjs

$ scope。$ apply()主要在定义$ scope时使用。 但是这种定义似乎并没有刷新名单。

HTML:

<div ng-repeat="feed in feedCtrl.feeds"></div>

控制器:

this.feeds = response.data;

4 个答案:

答案 0 :(得分:2)

只需使用新数据重新分配this.feeds ,即可刷新。

此外,您可以通过将范围注入控制器来调用$scope.$apply(),以便再次运行整个摘要周期并更新变量

在我看来,您遇到的问题是在功能中使用this.feeds无效,因为this是指function而不是original value }。

因此,请将this分配给变量vm

<强> var vm = this; and use vm.feeds = response.data

&#13;
&#13;
<!DOCTYPE html>
<html ng-app="myApp">

<head>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

	<script type="text/javascript">
		var myApp = angular.module('myApp',[])
		.controller('MyCtrl', function MyCtrl($timeout,$scope) {

			var vm = this;
			vm.feeds = ["Feed1","Feed2","Feed3","Feed4"];
            
            $timeout(function () {
       			vm.feeds = ["Changed Feed1","Changed Feed2","Changed Feed3","Changed Feed4"];
    		}, 2000);
			
		})
	</script>
</head>
<body ng-controller="MyCtrl as feedCtrl">
<p ng-repeat="data in feedCtrl.feeds">
	{{data}}
</p>

</body>

</html>
&#13;
&#13;
&#13;

上面的代码会在2秒后更改Feed。请运行上面的代码

Here is a working DEMO

答案 1 :(得分:0)

试试这个

&#13;
&#13;
<!DOCTYPE html>
<html ng-app="myApp">

<head>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

	<script type="text/javascript">
		var myApp = angular.module('myApp',[])
		.controller('MyCtrl', function MyCtrl() {


			this.values = ["Daily","Weekly","Monthly","Yearly"];

			this.updateValue = function (argument) {
				this.values = ["1","2","3","4"];				
			}


		})
	</script>
</head>
<body ng-controller="MyCtrl as ctrl">
<div ng-repeat="value in ctrl.values">
	{{value}}
</div>
<button ng-click="ctrl.updateValue()">
	updateValue
</button>
</body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这可能对您有所帮助

<body ng-app="myApp" ng-controller="appCtrl as ctrl">
<h1 ng-repeat="x in ctrl.records">{{x}}</h1>
<button ng-click="ctrl.records=['Bananna','Grapes'];">update records</button>
控制器中的

var app = angular.module("myApp", []);
app.controller("appCtrl", function() {  this.records = ["Mango","Apple","Orange"];    });

答案 3 :(得分:0)

在控制器中注入$ scope并在检索数据后使用$ scope。$ apply()。没问题,如果你正在使用&#34;这个&#34;。即

this.feeds = response.data;
$scope.$apply();

但是不要忘记在控制器中注入$ scope