如何在您尚未进入的视图中更改 Angular 中的范围。

How to change the scope in Angular in a view which you are not yet in.

我问过这个问题很多次了,但没有得到太多帮助。所以我现在问是否可以将范围中的值更改为您不在的视图中的控制器。当我指的是视图时,我指的是不同的 HTML 页面。

比方说,我在 view1.html 视图 1 中。该视图有两个按钮,按钮 1 和按钮 2。如果我单击按钮 1,将出现一个新视图; view2.html 其中包含一个粗体文本字段,例如 {{test}} 。当我点击 button1 时,我希望 $scope.test 成为 "button1"。同样,当我单击按钮 2 时,我希望打开相同的视图 (view2.html),但这次我希望范围为 "button2" 而不是 "button1"。

我想要这个的原因是为了避免创建许多 html 页面,因为一段时间后我会有很多不同的值。例如,如果我在第一页上有 10 个按钮 (view1.html),我不想创建 10 个 html 页面以便为您单击的每个按钮设置不同的值。我想要 1 html 页面可以根据单击的按钮显示不同的值。我正在使用 Appgyver Supersonic(类固醇)将其开发为应用程序。

我曾尝试显示和隐藏不同的粗体标签,但始终无法做到。正如您可能猜到的那样,我是 Angular 的菜鸟,但我从来没有收到一个直接的答案,即使我尝试了多少,这个答案在实践中也是有效的。所以请帮忙,给我一个简单的例子,你创建了两个 html 页面和一个 js。文件,以及如何从第一个 html 页面转到第二个页面并根据我在第一个视图中的选择仍然显示不同的值。谢谢!下面是我想要实现的示例代码,但在此示例中,当我单击按钮时范围不会更新,它保持不变。

示例代码

view1.html

<div ng-controller="IndexController">
<button class="button button-block button-assertive" ng-click="button1()" value="checkitems" >
  Button1
</button>
<button class="button button-block button-assertive" ng-click="button2()" value="checkitems" >
  Button2
</button>
</div>

Indexcontroller.js

angular
  .module('legeApp')
  .controller('IndexController', function($scope, supersonic, $filter) {  

$scope.test = 'test';

 $scope.button1= function(){   

     $scope.test= 'button1';

        var view = new supersonic.ui.View("legeApp#view2.html");
        var customAnimation = supersonic.ui.animate("flipHorizontalFromLeft");
        supersonic.ui.layers.push(view, { animation: customAnimation });
    };

 $scope.button2= function(){   

     $scope.test= 'button2';

        var view = new supersonic.ui.View("legeApp#view2.html");
        var customAnimation = supersonic.ui.animate("flipHorizontalFromLeft");
        supersonic.ui.layers.push(view, { animation: customAnimation });
    };
});

View2.html

<div ng-controller="IndexController">
<div class="card">
  <div class="item item-text-wrap">
    Test<b>{{test}} </b>
  </div>
</div>
    </div>

您可以使用 $rootScope.$emit$rootScope.$on 来处理不同 $scopecontroller 之间的通信。

angular
  .module('legeApp')
  .controller('IndexController', function($scope, $rootScope, supersonic, $filter) {
    $scope.button1= function(){   
       $rootScope.$emit('myCustomEvent', 'Data to send');
    };

  })
  .controller('IndexController2', function($scope, $rootScope, supersonic, $filter) {
    $rootScope.$on('myCustomEvent', function (event, data) {
      console.log(data); // 'Data to send'
    });
  });

您也可以使用该服务。

该服务提供全局variable.So您可以将服务注入到不同的控制器。