如何讓指令內(nèi)部的controller產(chǎn)生的資料傳到指令外部的控制器中
先說三種方法:
樓上回答的用廣播通信,$emit
向上,$broadcast
向下
service
共享數(shù)據(jù),就是把同一個service
注入到directive
和controller
中,然后操作這個service
的數(shù)據(jù)就好
當(dāng)然你的directive
如果在controller
的里面,本身就可以訪問到controller
的作用域(前提是沒創(chuàng)建獨(dú)立scope),直接在directive
的controller
中操作scope
就可以了
內(nèi)部 $scope.$emit("emit",data)
外部 $scope.$on("emit",function(ev,data){console.log(data)})
有很多種方法,看你的資料想要如何使用。
透過事件訂閱和廣播進(jìn)行分發(fā)
//$rootScope
$rootScope.$on('data-pass',function(event, data){ $rootScope.$broadcast('data-receive', data) })
// 傳遞數(shù)據(jù)的controller
$scope.$emit('data-pass', data)
// 需要數(shù)據(jù)的controller
$scope.$on('data-receiver', function(event, data){
// use data to do something
})
透過$scope的繼承特性改寫根作用域上的物件屬性值
// 根作用域
$rootScope.data = {}
// 傳遞數(shù)據(jù)的controller
$scope.data.record = {}
// 需要數(shù)據(jù)的controller
// use $scope.data.record to do something
透過angular公用模組用於資料存儲,注入到需要使用的controller裡
angular.factory('publicData',function(){
return {}
});
// 傳遞數(shù)據(jù)的controller
angular.controller('passController',function($scope, publicData){
publicData.record = {}
})
// 需要數(shù)據(jù)的controller
angular.controller('needController',function($scope, publicData){
// use publicData.record to do something
})