angularjs控制器间传值的五种方法
程序员文章站
2023-08-29 18:41:16
控制器间传值
1. 父作用域向子作用域传值
- broadcasted :从父级作用域广播至子级 scope
- $on()捕获事件
$broadcast(...
控制器间传值
1. 父作用域向子作用域传值
- broadcasted :从父级作用域广播至子级 scope - $on()捕获事件
$broadcast('myevent')
2. 子作用域向父作用域传值
- emitted :从子级作用域往上发射到父级作用域(相当于冒泡) - $on()捕获事件
$emit('myevent')
3.- 平级作用域resolve传值
- 使用resolve传值,传递的是一个对象 - 获取时需要将传递的对象的名注入后使用
resolve: { academicinfo: function () { if (type === 'add') { return null } else if (type === 'edit') { return academic } } }
4. 使用根作用域($rootscope)
- $rootscope相当于一个全局变量,在同一个angular.module("exampleapp")下可用 - $rootscope需要注入到控制器后再使用
5. 使用service服务
- 在同一个module下,不同的控制器可以访问同一个service服务 - 通过service服务里值的存储传递可实现控制器传值
完整demo:
<!doctype html> <html ng-app="exampleapp"> <head> <title>controllers</title> <script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <link href="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script> angular.module("exampleapp", []) .service("zipcodes", function($rootscope) { return { setzipcode: function(type, zip) { this[type] = zip; $rootscope.$broadcast("zipcodeupdated", { type: type, zipcode: zip }); } } }) .controller("simplectrl", function ($scope, zipcodes) { $scope.$on("zipcodeupdated", function (event, args) { $scope[args.type] = args.zipcode; }); $scope.setaddress = function (type, zip) { zipcodes.setzipcode(type, zip); console.log("type: " + type + " " + zip); } $scope.copyaddress = function () { $scope.zip = $scope.billingzip; } }); </script> </head> <body> <p class="well" ng-controller="simplectrl"> <h4>billing zip code</h4> <p class="form-group"> <input class="form-control" ng-model="zip"> </p> <button class="btn btn-primary" ng-click="setaddress('billingzip', zip)"> save billing </button> </p> <p class="well" ng-controller="simplectrl"> <h4>shipping zip code</h4> <p class="form-group"> <input class="form-control" ng-model="zip"> </p> <button class="btn btn-primary" ng-click="copyaddress()"> use billing </button> <button class="btn btn-primary" ng-click="setaddress('shippingzip', zip)"> save shipping </button> </p> </body> </html>
以上五中angularjs控制器传值方案在工作中应该是够用啦,恩,点个赞呗:)
end
上一篇: 没结婚时候