如何让指令内部的controller生成的数据传到指令外部的控制器中
Let’s talk about three methods first:
The one upstairs answered using broadcast communication, $emit向上,$broadcastdownside
$emit
$broadcast
service共享数据,就是把同一个service注入到directive和controller中,然后操作这个service is good
service
directive
controller
Of course your directive如果在controller的里面,本身就可以访问到controller的作用域(前提是没创建独立scope),直接在directive的controller中操作scope is fine
scope
Internal $scope.$emit("emit",data)External $scope.$on("emit",function(ev,data){console.log(data)})
Use independent scope, "=" two-way binding, and pass the data you want to bind through the parameters in the instruction.
There are many ways to use your data.
Distribution via event subscriptions and broadcasts
//$rootScope $rootScope.$on('data-pass',function(event, data){ $rootScope.$broadcast('data-receive', data) }) // 传递数据的controller $scope.$emit('data-pass', data) // 需要数据的controller $scope.$on('data-receiver', function(event, data){ // use data to do something })
Rewrite the object attribute value on the root scope through the inheritance feature of $scope
// 根作用域 $rootScope.data = {} // 传递数据的controller $scope.data.record = {} // 需要数据的controller // use $scope.data.record to do something
Use the angular public module for data storage and inject it into the controller that needs to be used
angular.factory('publicData',function(){ return {} }); // 传递数据的controller angular.controller('passController',function($scope, publicData){ publicData.record = {} }) // 需要数据的controller angular.controller('needController',function($scope, publicData){ // use publicData.record to do something })
Let’s talk about three methods first:
The one upstairs answered using broadcast communication,
$emit
向上,$broadcast
downsideservice
共享数据,就是把同一个service
注入到directive
和controller
中,然后操作这个service
is goodOf course your
directive
如果在controller
的里面,本身就可以访问到controller
的作用域(前提是没创建独立scope),直接在directive
的controller
中操作scope
is fineInternal $scope.$emit("emit",data)
External $scope.$on("emit",function(ev,data){console.log(data)})
Use independent scope, "=" two-way binding, and pass the data you want to bind through the parameters in the instruction.
There are many ways to use your data.