对于noob问题我很抱歉,我是AngularJS的新手。 我有一个服务和2个控制器,一个用于我的主页,第二个用于我想要动态创建的页面。
我想在我的服务中从我的第一个控制器(主页)设置一个对象,并在我的第二个控制器中获取此对象(在我将通过表单操作调用的新html页面上)并显示一些属性这个对象。
我该怎么做?
谢谢!
EDIT 我需要的样本:
index.html
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="app.js"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
First Controller
<button ng-click="add()">add</button>
{{data.value}}
<hr/>
<a href="index2.html">Aqui!</a>
</div>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="secondCtrl">
Second Controller
<button ng-click="add()">add</button>
{{data.value}}
<hr/>
</div>
</body>
</html>
http://plnkr.co/edit/sSBnE7gllFc0F6197cUD?p=info
答案 0 :(得分:2)
var app = angular.module('app', []);
app.service('dataService', function(){
var _data = {value:0};
return {
data : _data
};
});
app.controller('firstCtrl', function($scope,dataService){
$scope.data = dataService.data;
$scope.add = function(){
$scope.data.value ++;
};
});
app.controller('secondCtrl', function($scope,dataService){
$scope.data = dataService.data;
$scope.add = function(){
$scope.data.value ++;
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
First Controller
<button ng-click="add()">add</button>
{{data.value}}
<hr/>
</div>
<div ng-controller="secondCtrl">
Second Controller
<button ng-click="add()">add</button>
{{data.value}}
<hr/>
</div>
</body>
&#13;
答案 1 :(得分:2)
在这种情况下,您可以使用ngStorage https://github.com/gsklee/ngStorage,因为在完整页面重新加载后,服务中的数据将被销毁。
请在此处查看演示http://plnkr.co/edit/8b04wZ6btGwLodRuJr7V?p=preview
<强> JS:强>
var app = angular.module('app', ['ngStorage']);
app.controller('firstCtrl', function($scope, $localStorage) {
$scope.storage = $localStorage.$default({myValue: 0 });
});
app.controller('secondCtrl', function($scope, $localStorage) {
$scope.storage = $localStorage;
});
<强> HTML1 强>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
<script src="app.js"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
First Controller
<button ng-click="storage.myValue = storage.myValue + 1">{{storage.myValue}}</button>
{{service.data.value}}
<hr/>
<a href="index2.html">Aqui!</a>
</div>
</body>
</html>
<强> HTML2 强>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
<script src="app.js"></script>
<body ng-app="app">
<div ng-controller="secondCtrl">
Second Controller myValue is: {{storage.myValue}}
</div>
<a href="index.html">Page 1</a>
</body>
</html>
答案 2 :(得分:1)
将服务注入第一个控制器,在其上设置一个对象。将相同的服务注入第二个控制器和中提琴 - 对象就在那里!