简体   繁体   English

使用“ Controller as”语法的控制器之间的通信

[英]Communication between controllers using “Controller as” syntax

As I found on stackoverflow the proper way to communicate between angular controllers is by using services. 正如我在stackoverflow上发现的那样,在角度控制器之间进行通信的正确方法是使用服务。 There are few topics here which demonstrate how to do it by using $scope. 这里没有几个主题演示如何使用$ scope做到这一点。 However, this approach (using services) is not working for me if I use "controller as" syntax, without $scope. 但是,如果我在没有$ scope的情况下使用“ controller as”语法,这种方法(使用服务)对我不起作用。 Here is my example: 这是我的示例:

HTML HTML

<div ng-app="myapp">
    <div ng-controller="PersonCtrl as person">
        <p>{{ person.name['last'] }}</p>
    </div>
     <div ng-controller="PersonCtrl2 as person2">
         Change name <button type="button" ng-click="person2.changeName()"> To Ted</button>
     </div>
</div>

JS JS

var myapp = angular.module('myapp', []);

myapp.controller('PersonCtrl', function (myService1) {
    this.name = myService1.newName;
});

myapp.service('myService1', function() {
    this.newName = {'last': 'Bob'};
});


var PersonCtrl2 = function(myService1) {
    this.service = myService1;
};

PersonCtrl2.prototype.changeName = function() {
    alert('a');
    this.service.newName = {'last': 'Ted'};
};

myapp.controller('PersonCtrl2', PersonCtrl2);

Fiddle http://jsfiddle.net/vxQK7/ 小提琴 http://jsfiddle.net/vxQK7/

PS I also wanted to use $watch for update notification, but as far as I now, I can use it only from $scope and not by using "this"? PS我也想使用$ watch进行更新通知,但是到目前为止,我只能在$ scope中使用它,而不能使用“ this”?

as callmekatootie said you need to return something in your service but you also need not to break the reference of your model 正如callmekatootie所说,您需要在服务中返回某些内容,但同时也不需要破坏模型的引用

 this.name = myService1.newName

this would create a link betwin this.name and service.newName not to the value but to the actual object 这将创建this.name和service.newName之间的链接,而不是该值,而是实际对象

 this.service.newName = {'last': 'Ted'};

this would destroy the object to which the other controller is linked to and create a new one to of wich the other controller has no idea that exists. 这将销毁另一个控制器链接到的对象,并创建另一个控制器不存在的新对象。

the solution is very simple as posted in this link 该解决方案非常简单,如此链接中所述

http://jsfiddle.net/vxQK7/1/ http://jsfiddle.net/vxQK7/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM