如何通过双向绑定将数据从 HTML 发送到 angularjs 中的 $rootScope

How can I send data with two-way-binding from HTML to $rootScope in angularjs

我对angularjs知之甚少,我很喜欢里面的双向绑定。我知道如何使用 ng-model 将数据从 HTML 发送到控制器。现在我的问题是我在 app.js 中编写了一个函数,就像这样

 .run(function ($rootScope) {
        console.log($rootScope.test)
 }

这是我的 HTML

<input type="password" class="form-control" ng-model="test" 
      ng-change="vali_repassword()" ng-required="more"> 

我想在 ng-model 中得到 test ,如何实现?

在与您的 HTML 关联的控制器中,注入 $rootScope$scope 并在 $scope 中绑定 $rootScope 值,以便您可以在关联的 HTML 中使用该变量。

仅供参考,使用 $rootScope 共享数据是一种不好的做法。相反,有很多方法可以做到这一点。例如,改用服务。

.controller(function ($rootScope, $scope) {
  $scope.test = $rootScope.test;
}

<input type="password" class="form-control" ng-model="test" 
      ng-change="vali_repassword()" ng-required="more">

然后 onChange (vali_repassword) 您需要将值分配回 $rootScope.test 以确保该值也在 $rootScope 中更新。