Reputation: 3461
I'm using Angular to create a simple directive. I'd like to display the model properties x and y as attributes in the directive. However, instead of the values x and y in scope.textItems, I only get 'item.x' and 'item.y' as the values.
Can one of you tell me why?
thanks!
<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"}
];
}
Upvotes: 1
Views: 1042
Reputation: 364727
Do you want to show the values in the directive's template
? If so:
HTML:
<b-text-el ng-repeat="item in textItems" x="{{item.x}}" y="{{item.y}}">
Directive:
return {
restrict:'E',
scope: { x: '@', y: '@' },
replace: false,
template: '<span>text x={{x}} y={{y}}</span>',
....
Output:
text x=50 y=50text x=100 y=100
Also note that element.draggable();
should work (instead of $(element).draggable();
) since element should already be a wrapped jQuery element (if you include jQuery before including Angular).
Upvotes: 3
Reputation: 108501
You need to either $eval what's passed into the x and y attributes, OR you need to $watch them. Depending on your goals (and what you're passing in):
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();
}
Upvotes: 1