각도로 사용자 지정 지시문을 정의하고 싶습니다. 일부 사용자 지정 속성을 기반으로 경로를 계산할 수 있습니다.
HTML 코드 :
<div ng-controller="Ctrl">
<input ng-model="ratio" />
<hr/>
Image:
<span retina-src="{{server}}/{{originWidth}}x{{originHeight}}{{uri}}"
origin-width="111" origin-height="222" />
</div>
Angularjs 코드 :
angular.module('myapp', []).
controller('Ctrl', ['$scope',
function Ctrl($scope) {
$scope.ratio = 1;
$scope.server = "http://some.com";
$scope.uri = "/main.jpg";
$scope.name = "abc";
}
]).
directive('retinaSrc', ['$compile',
function($compile) {
return {
restrict: 'A',
scope: {
originWidth: '@originWidth',
originHeight: '@originHeight'
},
compile: function compile(tElement, tAttrs, transclude) {
var realPath = tAttrs.retinaSrc;
return {
post: function postLink(scope, iElement, iAttrs, controller) {
scope.$parent.$watch("ratio", function(o, v) {
scope.originWidth = scope.originWidth * scope.ratio;
scope.originHeight = scope.originHeight * scope.ratio;
console.log("realPath: " + realPath);
// !!! there is something wrong here
var value = $compile(realPath)(scope);
console.log(value);
iElement.text(value);
});
}
};
}
};
}
]);
다음과 retina-src
같이 텍스트를 볼 수 있습니다 .
{{server}}/{{originWidth}}x{{originHeight}}{{uri}}
그러나 나는 그것을 평가하는 방법을 모른다. $compile
내 코드에서 시도했지만 작동하지 않고 대신 몇 가지 오류를보고합니다.
Error: [jqLite:nosel] http://errors.angularjs.org/1.2.14/jqLite/nosel
at Error (native)
나는 또한 시도 scope.$eval(realPath)
했지만 다른 오류를보고합니다.
라이브 데모 : http://jsbin.com/mufokegayuqa/3/edit
곱슬 표현식을 바꾸려면 $ interpolate 서비스가 필요합니다. 예 : {{originWidth}}.
예:
var url = $interpolate(iAttrs.retinaSrc)(scope.$parent);
참고 : 지시문에 격리 된 범위가 있으므로 scope. $ parent가 필요합니다. $ interpolate 서비스를 디렉티브 함수에 삽입하는 것을 잊지 마십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다