두 가지 방법은 내 마음에 와서 :
- 당신은 imageDimention베이스/부모/어떤 범위에서 선언과 같은 객체 뭔가를하고 그 범위 격리를 통해 지시어와 공유하고 지침의 컨트롤러의 범위에서 할 수 있습니다 당신 해당 imageDimention 객체에 액세스하여 imageWidth 및 imageHeight 속성을 설정할 수 있습니다. 지침에서 이러한 속성을 설정하면 어떤뿐만 아니라 범위베이스/부모 /의 효과 취합니다 ImageController의 범위에서 다음 angular documentation
angular
.module('yourapp')
.directive('myImage', function() {
return {
restrict: 'E',
scope: {
imageDimention: '=imageDimention'
},
controller: 'ImageController'
};
});
에서 복사 범위 분리의
예, 당신은 같은 imageDimention 객체
에 액세스 할 수 있습니다
- ContextService를 만들면이 이미지 속성뿐만 아니라 다른 각도 구성 요소간에 데이터를 공유하는 데 사용할 수 있습니다. 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;
}
을 그리고 당신은 당신의 각 구성 요소로이 서비스를 주입 할 수 있습니다 (컨트롤러/지침/기타 서비스) 및 서비스이기 때문에 전역 개체의 일종으로 액세스를 싱글 톤, 이것은 당신을 데이터 공유 모듈로 제공 할 것입니다. 귀하의 경우에는
, 당신은 아마 개체를 선언해야이 컨트롤러 범위에 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();
});
}
})();
,
이게 도움이되기를 바랍니다.
내가 대답을 업데이트 할 수 있습니다. –
@Jwqq 업데이트 된 답변 확인 –