我正在使用Angular来创建一个简单的指令。我想将模型属性x和y显示为指令中的属性。但是,不是scope.textItems中的值x和y,而是仅将'item.x'和'item.y'作为值。
你能否告诉我为什么?谢谢!
<div id="b-main-container" class="b-main-container" ng-app="editorApp" ng-controller="EditorCtrl">
<div class="b-grid">
<div id="b-main" class="b-main g1080">
<b-text-el ng-repeat="item in textItems" x="item.x" y="item.y"">
</b-text-el>
</div><!-- end b-main -->
</div>
</div><!-- end grid -->
var myComponent = angular.module('components', []);
myComponent.directive("bTextEl", function () {
return {
restrict:'E',
scope: { },
replace: false,
template: '<span>text</span>',
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { console.log('here 1'); },
post: function linkFn(scope, element, attrs) {
$(element).draggable();
}
}
}
};
});
var myEditorApp = angular.module('editorApp', ['components']);
function EditorCtrl($scope) {
$scope.textItems = [
{"id": "TextItem 1","x":"50","y":"50"},
{"id": "TextItem 2","x":"100","y":"100"}
];
}
答案 0 :(得分:3)
是否要在指令template
中显示值?如果是这样的话:
HTML:
<b-text-el ng-repeat="item in textItems" x="{{item.x}}" y="{{item.y}}">
指令:
return {
restrict:'E',
scope: { x: '@', y: '@' },
replace: false,
template: '<span>text x={{x}} y={{y}}</span>',
....
输出:
text x=50 y=50text x=100 y=100
另请注意,element.draggable();
应该有效(而不是$(element).draggable();
),因为元素应该已经是一个包装的jQuery元素(如果在包含Angular之前包含jQuery)。
答案 1 :(得分:1)
你需要$ eval传递给x和y属性的东西,或者你需要$ watch。取决于您的目标(以及您传递的内容):
post: function linkFn(scope, element, attrs) {
//this will get their values initially
var x = scope.$eval(attrs.x),
y = scope.$eval(attrs.y);
//this will watch for their values to change
// (which also happens initially)
scope.$watch(attrs.x, function(newX, oldX) {
// do something with x's new value.
});
$(element).draggable();
}