Angularjs Controller間通訊的幾種方法

先說最簡單的,適合簡單數據html

1、使用controller asangularjs

<body ng-controller="ParentCtrl as parent">
    <input ng-model="parent.name" /> {{parent.name}}
    <div ng-controller="ChildCtrl as child">
      <input ng-model="child.name" /> {{child.name}} - {{parent.name}}
    </div>
</body>

這樣parentCtrl中的數據也能夠顯示在嵌套在其中的childCtrl了app

2、使用$rootScope 或 $parent函數

<body ng-controller="ParentCtrl">
    <input ng-model="name" /> {{name}}
    <div ng-controller="ChildCtrl">
        <input ng-model="name" /> {{name}} - {{$parent.name}}
    </div>
</body>

3、使用$broadcast,$emit和$onspa

  • 從上往下—— $broadcast 把事件廣播給全部子controller
  • 從下往上—— $emit 將事件冒泡傳遞給父controller
  • $on     ——  angularjs的事件註冊函數
<div ng-app="app" ng-controller="parentCtrl">
    <div ng-controller="childCtrl1">name :
        <input ng-model="name" type="text" ng-change="change(name);" />
    </div>
    <div ng-controller="childCtrl2">Ctr1 name:
        <input ng-model="ctrl1Name" />
    </div>
</div>
angular.module("app", []).controller("parentCtrl",function ($scope) {
    //註冊Ctrl1NameChange事件
    $scope.$on("Ctrl1NameChange", function (event, msg) {
        console.log("parent", msg);
        $scope.$broadcast("Ctrl1NameChangeFromParent", msg);
    });
}).controller("childCtrl1", function ($scope) {
    $scope.change = function (name) {
        console.log("childCtrl1", name);
//冒泡Ctrl1NameChange事件,將name傳給父級controller $scope.$emit(
"Ctrl1NameChange", name); }; }).controller("childCtrl2", function ($scope) { // $scope.$on("Ctrl1NameChangeFromParent",function (event, msg) { console.log("childCtrl2", msg); $scope.ctrl1Name = msg; }); });

jsfiddle連接:http://jsfiddle.net/whitewolf/5JBA7/15/.net

參看:code

  • http://www.cnblogs.com/whitewolf/archive/2013/04/16/3024843.html
  • http://stackoverflow.com/questions/21287794/angularjs-controller-as-syntax-clarification
相關文章
相關標籤/搜索