孤立的指令范围内的本地数据

时间:2014-03-25 20:14:43

标签: javascript html angularjs angularjs-directive

我正在编写我的第一个指令之一,我想在指令范围内创建一些存根数据。

这是指令:

angular.fraskDirectives.directive("recipientsSelector", [

  function() {
      return {
          restrict: "E",
          replace: true,
          scope: {
             recipients: "=",
             theText: "test",
             users: [{
                 username: "aaa"
             }, {
                 username: "aab"
             }, {
                 username: "abb"
             }, {
                 username: "bbb"
             }, {
                 username: "bbc"
             }]
         },
         templateUrl: "partials/recipientsSelector.html"
     };
   }
]);

这是模板:

<div>
<div contenteditable>
    <p>{{theText}}</p>
</div>

<ul class="suggestions">
    <li ng-repeat="user in users">
        {{user.username}}
    </li>
</ul>

但是“text”字段和user字段都没有绑定。我的意思是ul为空,{{text}}在页面上看起来像“{{text}}”。

如何在我的指令隔离范围内创建本地数据?

由于

1 个答案:

答案 0 :(得分:1)

要仅使用未绑定到指令之外的任何内容的“本地”数据填充范围,请使用如下链接函数:

angular.fraskDirectives.directive("recipientsSelector", [ function() {
    return {
        restrict: "E",
        replace: true,
        scope: {
            recipients: "=" // note that theText and users are missing
        },
        templateUrl: "partials/recipientsSelector.html",
        link: function (scope, elem, attrs) {
            scope.theText = "test";
            scope.users = [{
                username: "aaa"
            }, {
                username: "aab"
            }, {
                username: "abb"
            }, {
                username: "bbb"
            }, {
                username: "bbc"
            }];
        }
    };
}]);

另一种方法是将控制器分配给指令并在控制器中填充范围。