数据绑定在特定情况下不起作用(AngularJS)

Data binding doesn't work in a specific case (AngularJS)

本文关键字:AngularJS 不起作用 在特定情况下 数据绑定      更新时间:2023-09-26

这是我的问题:
当我在修改模型"urlservicerest"后单击按钮时,我的属性"$scope.urlservicerest"保持初始化为"hello"。
我尝试用 $scope.$apply 更新数据,但没有成功。我不明白为什么"$scope.urlservicerest"没有更新,而已经创建了数据绑定。

//file.html
<input type="input" ng-model="urlservicerest"></
<button type="button"  ng-click="refresh()"> Rafraichir </button>

//script.js:
var field = $scope.urlservicerest = "hello";
  $scope.refresh = function () {
    alert(field);
}

Angular 绑定到作用域属性。 因此,在您的情况下,当输入值更改时,$scope.urlservicerest将是双向绑定的。

您正在提醒 field 的值,该值不是双向绑定的。

为作用域属性添加第二个警报会显示$scope.urlservicerest已正确绑定:

  $scope.refresh = function () {
    alert(field);
    alert($scope.urlservicerest);
  }

这个 plunker 证明了这一点。

我已经更新了JS小提琴的演示 希望对您有所帮助

示例 JSFiddle

我认为您需要在页面中添加<html data-ng-app="">