3 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
您需要使用服務(wù),因?yàn)榉?wù)會(huì)在您的應(yīng)用程序的整個(gè)生命周期中持續(xù)存在。
假設(shè)您要保存與用戶有關(guān)的數(shù)據(jù)
這是您定義服務(wù)的方式:
app.factory("user",function(){
return {};
});
在第一個(gè)控制器中:
app.controller( "RegistrationPage1Controller",function($scope,user){
$scope.user = user;
// and then set values on the object
$scope.user.firstname = "John";
$scope.user.secondname = "Smith";
});
app.controller( "RegistrationSecondPageController",function($scope,user){
$scope.user = user;
// and then set values on the object
$scope.user.address = "1, Mars";
});

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
該服務(wù)將起作用,但是僅使用普通作用域和控制器來(lái)實(shí)現(xiàn)此服務(wù)的邏輯方法是設(shè)置控制器和元素,以使其反映模型的結(jié)構(gòu)。特別是,您需要一個(gè)父元素和一個(gè)建立父作用域的控制器。表單的各個(gè)頁(yè)面應(yīng)位于作為父級(jí)的子級(jí)的視圖中。即使更新子視圖,父范圍也將保留。
我假設(shè)您正在使用ui-router,以便可以嵌套嵌套的命名視圖。然后用偽代碼:
<div ng-controller="WizardController">
<div name="stepView" ui-view/>
</div>
然后,WizardController定義您要在多頁(yè)表單的各個(gè)步驟中保留的范圍變量(我將其稱(chēng)為“向?qū)А保?。然后,您的路線只會(huì)更新stepView。每個(gè)步驟可以具有自己的模板,控制器和范圍,但是它們的范圍在頁(yè)面之間丟失。但是WizardController中的作用域保留在所有頁(yè)面中。
要從子控制器中更新WizardController范圍,您將需要為每個(gè)范圍變量使用類(lèi)似的語(yǔ)法$scope.$parent.myProp = 'value'或setMyProp在WizardController上定義一個(gè)函數(shù)。否則,如果嘗試直接從子控制器設(shè)置父作用域變量,則最終只會(huì)在子項(xiàng)本身上創(chuàng)建一個(gè)新的作用域變量,從而遮蓋了父變量。
有點(diǎn)難以解釋?zhuān)瑢?duì)于缺乏完整的示例,我深表歉意?;旧希枰粋€(gè)父控制器來(lái)建立一個(gè)父作用域,該作用域?qū)⒈A粼诒韱蔚乃许?yè)面中。

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
數(shù)據(jù)可以通過(guò)兩種方式在控制器之間傳遞
$rootScope
模型
下面的示例演示了使用模型傳遞值
app.js
angular.module('testApp')
.controller('Controller', Controller)
.controller('ControllerTwo', ControllerTwo)
.factory('SharedService', SharedService);
SharedService.js
function SharedService($rootScope){
return{
objA: "value1",
objB: "value2"
}
}
//修改控制器A中的值
Controller.js
function Controller($scope, SharedService){
$scope.SharedService = SharedService;
$scope.SharedService.objA = "value1 modified";
}
//訪問(wèn)controllertwo中的值
ControllerTwo.js
function ControllerTwo($scope, SharedService){
$scope.SharedService = SharedService;
console.log("$scope.SharedService.objA"+$scope.SharedService.objA); // Prints "value1 modified"
}
- 3 回答
- 0 關(guān)注
- 547 瀏覽
添加回答
舉報(bào)