Angularjs controller之间的通信
生活随笔
收集整理的這篇文章主要介紹了
Angularjs controller之间的通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
剛剛看了網上的一些關于控制器之間的通信;然后結合自己項目做了一些,這里主要做的是二個同級之間的controller通信。
Html:
1 <html> 2 <script src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script> 3 <body> 4 <div ng-app="app"> 5 <div ng-controller="childCtr1">name : 6 <input ng-model="name" type="text" /> 7 </div> 8 <div ng-controller="childCtr2">Ctr1 name: 9 {{ctr1Name}} 10 </div> 11 </div> 12 </body> 13 </html>上面的html代碼設置了2個同級的控制器,現在childCtr2需要childCtr1的參數來顯示相關信息,下面是控制器childCtr1的代碼:
1 angular.module("app", []) 2 .controller("childCtr1", function ($scope) { 3 $scope.$watch("name",function (){//監聽綁定“name",當發生改變時發送消息; 4 //alert("123"); 5 $scope.$emit("Ctr1NameChange", $scope.name);//發送名為Ctr1NameChange的消息,值為$scope.name 6 }); 7 });下面是childCtr2的代碼:
angular.module("app", []) .controller("childCtr2", function ($scope) {$scope.$on("Ctr1NameChange",//監聽有沒有名為”Ctr1NameChange“的消息,如果有,則執行下面函數function (event, msg) {console.log("childCtr2", msg);$scope.ctr1Name = msg;}); });以上是針對控制器分離的文件寫的不同形式;當然也可以將他們合并到一個頁面
1 angular.module("app", []) 2 .controller("childCtr1", function ($scope) { 3 $scope.$watch("name",function (){ 4 //alert("123"); 5 $scope.$emit("Ctr1NameChange", $scope.name); 6 }); 7 }).controller("childCtr2", function ($scope) { 8 $scope.$on("Ctr1NameChange", 9 10 function (event, msg) { 11 console.log("childCtr2", msg); 12 $scope.ctr1Name = msg; 13 }); 14 });還有很多控制器之間的通信方法,包括server的factory,可以參考:http://jsbin.com/hopazo/5/edit?html,css,js,output
轉載于:https://www.cnblogs.com/tiedaweishao/p/4798651.html
總結
以上是生活随笔為你收集整理的Angularjs controller之间的通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么对兴业银行信用卡进行销卡?销卡要注意
- 下一篇: 交行Kindle优逸白金卡额度多少?额度