2つの方法が私の心に来る:
- あなたをあなたがimageDimentionのようなオブジェクトの何かがベース/親/どんなスコープで宣言していることができますし、それがスコープ分離を通じてディレクティブと共有しているし、次にディレクティブのコントローラの範囲からそのimageDimentionオブジェクトにアクセスして、imageWidthプロパティとimageHeightプロパティを設定できます。ディレクティブでこれらのプロパティを設定すると、どのような範囲だけでなく/ベース/親に有効になります:angular documentation
angular
.module('yourapp')
.directive('myImage', function() {
return {
restrict: 'E',
scope: {
imageDimention: '=imageDimention'
},
controller: 'ImageController'
};
});
からコピーされた範囲の分離の
例を、次に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更新された回答を確認してください –