1

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"}
  ];
}
4

2 回答 2

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();),因为 element 应该已经是一个包装的 jQuery 元素(如果您在包含 Angular 之前包含了 jQuery)。

于 2013-01-28T21:58:57.757 回答
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();

            }
于 2013-01-28T20:27:18.750 回答