gpt4 book ai didi

angularjs - 一次绑定(bind): update model and re-render view

转载 作者:行者123 更新时间:2023-12-03 22:05:48 25 4
gpt4 key购买 nike

我想知道是否可能,使用 Angular 一次绑定(bind),在模型更新后完全重新渲染 View /模板,也可以通过重新编译模板。
例如,在按下按钮时,可能是 react 的工作方式:我更新模型并明确强制更新 View 。
基本上这是我想要实现的目标:

// controller
angular.module('app', []).controller('AppCtrl', function($scope) {
$scope.items = [
{id: 1},
{id: 2},
{id: 3}
];

$scope.addAndRefresh = function() {
$scope.items.push({id: 4});
// manually call render logic here???
};
});


<!-- HTML template -->
<div ng-repeat="item in ::items">
{{item.id}}
</div>
<button ng-click="addAndRefresh()">Add</button>

通过单击“添加”按钮,我想刷新 View 以查看新添加的项目。

最佳答案

我也试图想办法优雅地做到这一点。我希望框架中内置了一些东西来刷新一次性绑定(bind)。我想出的只是使用 ngIf 删除我想要刷新的元素并将其添加回来。

这是一个演示。单击添加项目按钮,您会看到列表确实 不是 由于一次性绑定(bind)重复而刷新。检查刷新值并再次单击,项目将被更新:

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

app.controller('RefreshCtrl', function($scope, $timeout) {
var counter = 4;

$scope.visible = true;

$scope.items = ['Item1', 'Item2', 'Item3'];

$scope.addItem = function() {

if ($scope.refresh) {
$scope.visible = false;
}

$scope.items.push('Item' + counter);

counter++;

$timeout(function() {
$scope.visible = true;
});
};

});
<script src="https://code.angularjs.org/1.3.17/angular.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<div ng-app="demo" ng-controller="RefreshCtrl" class="container">
<button class="btn btn-default" ng-click="addItem()">Add Item</button>
<input type="checkbox" ng-model="refresh" />Refresh Values
<div ng-if="visible">
<h3 ng-repeat="item in ::items">{{item}}</h3>
</div>

<p>Items Array: {{items}}</p>
</div>

关于angularjs - 一次绑定(bind): update model and re-render view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31271093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com