在我的情况下,如何将数据从指令传递到父范围
How to pass data from directive to parent scope in my case?
我有一个关于指令和控制器的问题。
在我的例子中,我想把数据从指令传递到控制器。
模板的html<img ng-src=“{{url}}” image-detect />
<div>width: {{width of image}}</div> // how do I show the value here
<div>height: {{height of image}}</div>
指令(function () {
angular
.module(‘myApp’)
.directive(‘imageDetect’, imageDetect);
function imageDetect() {
var directive = {
'restrict': 'A',
'controller': imageController
};
return directive;
}
function imageController($scope, $element) {
$element.on('load', function() {
$scope.imageWidth = $(this).width();
$scope.imageHeight = $(this).height();
//not sure what to do to pass the width and height I calculate in directive to the parent
});
}
})();
我如何将imageWidth
和imageHeight
传递到父作用域并在模板中显示它?非常感谢!
我想到了两个方法:
- 你可以在base/parent/whatever作用域上声明一个像imagedimension这样的对象,然后通过作用域隔离让它与指令共享,然后从指令的控制器的作用域你可以访问那个imagedimension对象并设置它的imageWidth和imageHeight属性。在指令中设置这些属性也会在base/parent/whatever范围内生效:
作用域隔离示例,复制自angular文档
angular
.module('yourapp')
.directive('myImage', function() {
return {
restrict: 'E',
scope: {
imageDimention: '=imageDimention'
},
controller: 'ImageController'
};
});
然后在ImageController的作用域中你可以访问同样的imagedimension对象
- 创建一个ContextService,它可以用于在不同的angular组件之间共享数据,而不仅仅是这些图像属性。有一个比较通用的ContextService是很好的,这样它就可以被重用/通用。
ContextService可以是这样的:
angular.module('yourapp')
.factory('ContextService', ContextService);
function ContextService() {
var service = {};
var data = {};
service.set = set;
service.get = get;
function set(key, value) {
if(key !== null && key !== undefined){
data[key] = value;
}
}
function get(key) {
return data[key];
}
return service;
}
然后你可以把这个服务注入到你的angular组件(控制器/指令/其他服务)中,并把它作为某种全局对象来访问,因为服务是单例的,它将作为数据共享模块为你服务。
在你的情况下,你可能有一个附加到视图的控制器,所以假设你有这个控制器,应该声明一个对象,说image
在这个控制器范围:
$scope.image = {
url: 'imageUrl'
width: '0px',
height: '0px',
}
那么你的html模板应该是这样的:
<img ng-src="{{image.url}}" image-detect />
<div>width: {{image.width}}</div>
<div>height: {{image.height}}</div>
你的指令应该是这样的:
(function () {
angular
.module(‘myApp’)
.directive(‘imageDetect’, imageDetect);
function imageDetect() {
var directive = {
'restrict': 'A',
'scope': {
'image': '=image'
},
'controller': imageController
};
return directive;
}
function imageController($scope, $element) {
$element.on('load', function() {
//here you can access image object from scope which is same as controller that is attached to the view
$scope.image.width = $(this).width();
$scope.image.height = $(this).height();
});
}
})();
相关文章:
- AngularJS指令范围约束问题重复出现
- AngularJS:从控制器访问特定的指令范围
- 隔离范围-仅在指令范围内定义的值必须执行更改
- 指令范围
- 在ng重复中使用时的指令范围
- 角度指令模板输入不会更新指令范围
- 属性内的角度指令范围继承
- AngularJS:如何在指令范围的对象发生变化时更新与控制器作用域相关联的控制器作用域
- 如何从父指令/控制器访问指令范围
- AngularJS:在成功的HTTP请求后更新指令范围
- 购物指令范围问题
- 角度指令范围为空
- 在指令“范围”中需要值属性
- AngularJS 指令范围和$compile - 返回空白的变量
- AngularJS指令范围似乎只接受一个参数
- AngularJS :如何从相同的指令控制器访问指令范围
- 通过指令范围传递对象不起作用
- 指令范围重写父值
- 角度指令 - 范围返回 0 而不是值
- AngularJS 父指令范围来自内部 ng-transclude