AngularJS将数组插入指令中的字符串

AngularJS interpolates array to string inside directive

本文关键字:字符串 指令 插入 数组 AngularJS      更新时间:2023-09-26

TL;DR指令将数组插入为字符串
http://plnkr.co/edit/ZwV8jmi0tUTgezWlEq3S?p=preview

这是代码:
index.html

<!DOCTYPE html>
<html data-ng-app="foo">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body data-ng-controller="FooCtrl">
    <ul data-foo="{{foo.bar}}">
      <li data-ng-repeat="bar in foo.bar">
        {{bar}}
      </li>
    </ul>
  </body>
</html>

app.js

!(function(ng) {
  'use strict';
  FooCtrl.$inject = ['$scope'];
  function FooCtrl($scope) {
    $scope.foo = {
      bar: [
        'foo',
        'bar'
      ]
    };
  }
  function FooDirective() {
    return {
      restrict: 'A',
      scope: {
        model: '@foo'
      },
      link: function($scope) {
        var watcher = function(model) {
          console.log(model, typeof model);
        };
        $scope.$watch('model', watcher, true);
      }
    };
  }
  ng.module('foo', [])
    .controller('FooCtrl', FooCtrl)
    .directive('foo', FooDirective);
})(window.angular);

为什么我有"typeof model"字符串而不是数组?

如果您想绑定父作用域的实际数组,请使用:

scope: {
  model: '=foo'
}

当使用@foo时,您只是在绑定表达式{{foo.bar}}的结果。在您的情况下,数组foo的字符串解释。

添加

或者,当您使用&符号时,您可以从隔离作用域调用父作用域上的表达式:

scope: {
  model: '&foo'
}

并在您的指令中使用进行评估

model().bar