我已经多次问过这个问题,但没有得到太多帮助。所以我现在问是否可以将作用域中的值更改为您不在的 View 中的 Controller 。当我提到 View 时,我指的是不同的 HTML 页面。
可以说,我在 View 1 中,即 view1.html。该 View 有两个按钮,按钮 1 和按钮 2。如果我单击按钮 1,将出现一个新 View ; view2.html 包含一个粗体文本字段,例如 {{test}} 。当我单击“button1”时,我希望 $scope.test 为“button1”。同样,当我单击按钮 2 时,我希望打开相同的 View (view2.html),但这次我希望范围为“button2”而不是“button1”。
我想要这个的原因是为了避免创建许多 html 页面,因为一段时间后我会有许多不同的值。例如,如果我在第一页 (view1.html) 上有 10 个按钮,我不想创建 10 个 html 页面以便为您单击的每个按钮提供不同的值。我想要 1 个 html 页面,可以根据单击的按钮显示不同的值。我正在使用 Appgyver Supersonic (Steroids) 将其开发为应用程序。
我尝试过显示和隐藏不同的粗体标签,但始终无法做到。正如你可能猜到的那样,我是 Angular 的菜鸟,但我从来没有收到过一个直接的答案,即使我尝试了很多,这个答案在实践中也是有效的。所以请帮忙,给我看一个简单的例子,你创建了两个 html 页面和一个 js。文件,以及如何从第一个 html 页面转到第二个 html 页面,并且仍然根据我在第一个 View 中的选择显示不同的值。谢谢!下面是我想要实现的示例代码,但在这个示例中,当我单击按钮时,范围不会更新,它保持不变。
示例代码
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>
索引 Controller .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
来处理不同$scope
或 Controller 之间的通信
.
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'
});
});
关于javascript - 如何在您尚未进入的 View 中更改 Angular 的范围。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28208523/