【问题标题】:Angular Directive: Unable to bind to model propertiesAngular 指令:无法绑定到模型属性
【发布时间】:2013-01-28 19:35:20
【问题描述】:

我正在使用 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"}
  ];
}

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您想显示指令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
    

    Fiddle.

    还要注意element.draggable(); 应该可以工作(而不是$(element).draggable();),因为元素应该已经是一个包装好的 jQuery 元素(如果你在包含 Angular 之前包含了 jQuery)。

    【讨论】:

    • 请注意:scope: {} 会将您的指令的范围与它所放入的范围隔离开来。
    • ...也就是说,两个答案都是有效答案,这取决于你想做什么。马克知道他的东西。
    • 然而,这可能是最干净的方法。如果添加另一个作用域会占用更多内存。
    【解决方案2】:

    您需要对传入 x 和 y 属性的内容进行 $eval,或者您需要对它们进行 $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();
    
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 2020-12-19
      • 2018-12-03
      • 1970-01-01
      相关资源
      最近更新 更多