Javascript 在我的例子中,如何将数据从指令传递到父范围?
我有一个关于指令和控制器的问题 在本例中,我希望将数据从指令传递到控制器 模板htmlJavascript 在我的例子中,如何将数据从指令传递到父范围?,javascript,angularjs,directive,Javascript,Angularjs,Directive,我有一个关于指令和控制器的问题 在本例中,我希望将数据从指令传递到控制器 模板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> 如何将imageWidth和imageHeight传递
<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>
如何将
imageWidth
和imageHeight
传递到父作用域并在模板中显示?非常感谢 我想到了两种方法:
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;
}
然后你可以将这个服务注入你的角度组件(控制器/指令/其他服务)并作为某种全局对象访问它,因为服务是单例的,这将作为数据共享模块为你服务
在您的情况下,您可能有一个附加到视图的控制器,因此假设您有该控制器,应该在此控制器作用域上声明一个对象,例如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();
});
}
})();
我希望这会有帮助
<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();
});
}
})();