var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return {message: "I'm data from a service"}
})
function FirstCtrl($scope, Data){
$scope.data = Data;
}
function SecondCtrl($scope, Data){
//I want to send a string to the service so that the view associated with FirstCtrl is updated.
}
好的,我们以此代码为例。如何从SecondCtrl中设置消息字符串,以便更新与FirstCtrl绑定的视图?
答案 0 :(得分:0)
你可以做的一件事是创建另一个像这样的父控制器,并将常见的东西放到两个控制器
<div ng-controller="parentController">
<div ng-Controller="pageOneController">
<input placeholder="{{placeholder}}" type="text" />
</div>
<div ng-Controller="pageTwoController">
<--other html-->
</div>
</div>
app.controller('parentController', ['$scope', function($scope) {
$scope.placeholder = "this is common to both child controllers";
}]);
答案 1 :(得分:0)
您可以使用服务(工厂)在控制器之间共享数据,但不会直接使用$ scope。
请参阅此视频进行演示:
https://egghead.io/lessons/angularjs-sharing-data-between-controllers
竖起大拇指为egghead \ o /
编辑:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function() {
return {message: "I'm data from a service"}
})
function FirstCtrl($scope, Data){
$scope.data = Data;
}
function SecondCtrl($scope, Data){
$scope.data = Data;
// Simply set the message or bind it to an input on your view:
$scope.data.message = 'new value'
}
以下是演示:http://jsfiddle.net/suhvtr5r/
如果这不起作用,请与我们分享您的观点
答案 2 :(得分:0)
如果你想这样做,你需要在服务中使用getter和setter,fiddle可以帮助你:
HTML:
<div ng-app="myApp">
<div ng-controller="FirstCtrl">my first cotroller : {{data.message}}</div>
<div ng-controller="SecondCtrl">my second controller :
<input type="text" ng-model="data.message" ng-change="update()">
</div>
</div>
角:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return {
message: '',
get: function () {
alert("DasdaS");
return this.message;
},
set: function (secondCtrlStr) {
this.message = secondCtrlStr;
}
};
})
function FirstCtrl($scope, Data) {
$scope.data = Data;
}
function SecondCtrl($scope, Data) {
$scope.update = function () {
Data.set($scope.data.message);
};
}