为什么我的指令中没有这个字段绑定?

时间:2014-12-02 21:04:42

标签: angularjs angularjs-directive

我有一个对dataSourceModel范围变量进行双向绑定的指令,但由于某种原因,它在指令中显示为未定义。我在这里做错了吗?

Plunker:http://plnkr.co/edit/LxWMbY9qtDSBUPWNqWV7?p=preview

代码:

HTML:

<div ng-controller='TestCtrl'>
  <test-directive 
      selected-id='selectedId' 
      data-source-model='workOrderItems'>  <!-- This does not work -->
  </test-directive>
  {{workOrderItems}}  <!-- this works -->
</div>

脚本:

var app = angular.module("testApp", []);

app.controller('TestCtrl', ['$scope', function ($scope) {
    $scope.workOrderItems = 'abcd'; 
    $scope.selectedId = '123';
}]);

app.directive('testDirective',function () {
    return {
        restrict: 'E',
        scope: {
          selectedId: '=',
          dataSourceModel: '='
        },
        replace: true,
        template: "<div></div>",
        link: function (scope, element, attrs) {
          console.log(scope.selectedId, scope.dataSourceModel);
        }
    }
});  

1 个答案:

答案 0 :(得分:3)

data-是自定义HTML5属性的前缀,因此data-source-model='workOrderItems'在您的指令中仅转换为sourceModel

尝试将您的指令属性重命名为不以数据开头的内容(或将其作为data-data-source-model在HTML中引用)并且它应该可以正常工作。