Angularjs 从控制器B更新控制器A的$scope

Angularjs 从控制器B更新控制器A的$scope,angularjs,Angularjs,好的,让我们以这段代码为例。如何从SecondCtrl内部设置消息字符串,以便更新与FirstCtrl绑定的视图?您可以做的一件事是创建另一个这样的父控制器,并将公共内容放在两个控制器上 var myApp = angular.module('myApp', []); myApp.factory('Data', function() { return {message: "I'm data from a service"} }) function FirstCtrl($scope, D

好的,让我们以这段代码为例。如何从SecondCtrl内部设置消息字符串,以便更新与FirstCtrl绑定的视图?

您可以做的一件事是创建另一个这样的父控制器,并将公共内容放在两个控制器上

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.
}

app.controller('parentController',['$scope',函数($scope){
$scope.placeholder=“这对两个子控制器都是通用的”;
}]);

您可以使用服务(工厂)在控制器之间共享数据,但不能直接使用$scope

请参阅此视频进行演示:

竖起大拇指支持egghead\o/

编辑:

下面是一个演示:


如果这不起作用,请与我们分享您的观点

如果您想做到这一点,您需要getter和setter为您提供服务,以下是为您解决问题的方法:

HTML:


更新的问题。。如果你能再看一眼,我想你的答案非常接近,我将不胜感激。这完全是复制和粘贴的书呆子链接,你根本不做任何新的事情!是的@AliAmiri这个主题没有太多可添加的内容,书呆子链接很棒,我只是添加了小提琴来更好地演示和现场展示。虽然你的解决方案运行得很好,但它添加了一些额外的代码,对于这样的简单情况来说,这些代码并不是必需的。不,你需要一个setter,getter对于这种情况来说不是必需的,我只是把它放在代码中,但是你需要一个setter,这是一种正确的方法,egghead只是展示了如何在两个控制器中设置一个变量,这个解决方案不适用于字符串发生最简单变化的情况,因此您需要在工厂中拥有一个功能。当然,我同意,最好展示两个不同的解决方案,让@that1guyoverhr决定哪个更适合他,并在过程中学习,如果我的评论听起来像是批评,我很抱歉,只是缺少英语练习:)这感觉有点粗略,不是吗?我更新了我的问题。。有什么好主意吗?谢谢你的帮助!
<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";
}]);
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' 
}
<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);
    };
}