为什么即使使用 angular 的就绪功能,在我们单击文本框和屏幕后 $scope.value 仅显示为预填充文本框

Why $scope.value is only showing as prefilled textbox after we click on Text box and screen even using angular's ready function

我正在尝试在就绪函数中使用 $scope.lastName="ThisIsLastname" 设置名为 lastName 的 ng-model 的值。我可以设置值,它也可以设置,正如我在控制台中看到的那样,但问题是值没有出现在文本框本身上(文本框未预填充)。仅当我单击文本框然后单击屏幕中的任意位置时,文本框才会被预填充。

<input type="text" ng-model="lastName" /> <!-- this textbox should be prefilled when screen load using ng-model only -->


angular.element(document).ready(function () {
    console.log("is ready now");
    $scope.lastName="ThisIsLastname"; //set value
    console.log($scope.lastName); // I can see that value has been set successfully.
});

因此,当我重新加载页面时,我可以看到一旦调用就绪函数,该值就会打印在控制台上,但是我可以看到空文本框(姓氏的值未显示在文本框中)。

但是当我第一次点击那个空的文本框,然后点击屏幕上的任何地方时,文本框的值出现了。我不明白是什么让它现在出现,但在调用就绪函数时不出现。

我不需要替代解决方案,我想知道为什么会这样!

.ready() 不是 angularjs 的一部分,而是 jqlite (jquery) 的一部分。因此,即使您正在分配 $scope.value,您也已经启动摘要循环来更新 dom。

您可以在将 $scope.value 分配给 运行 摘要循环后添加 $scope.$apply()。

在angularjs中,angular.element是一个jqLite对象


用归零 $timeout 包装代码以触发摘要循环:

console.log("is ready now");

$timeout(function(){      
  $scope.lastName="ThisIsLastname";    
}); 

console.log($scope.lastName);