【问题标题】:AngularJS custom directive ng-repeat, Cannot call method 'insertBefore' of nullAngularJS 自定义指令 ng-repeat,无法调用 null 的方法“insertBefore”
【发布时间】:2014-01-24 04:12:03
【问题描述】:

在我的自定义AngularJS google maps directive中,我有map指令和marker指令,marker指令需要map指令。

以下是我的问题的简化版本,我不能使用 ng-repeat。

<!DOCTYPE html>
<html ng-app="testapp">
<head>
<script src="http://code.angularjs.org/1.2.5/angular.js"></script>
<script>
var testapp = angular.module('testapp', []);
testapp.directive('map', [
  function () {
    return {
      restrict: 'E',
      controller: function($scope) {
      },
      link: function (scope, element, attrs) {
        element.html("this will be a map");
      }
    };
  }
]);
testapp.directive('marker', [
  function () {
    return {
      require: '^map',
      restrict: 'E',
      link: function (scope, element, attrs, mapController) {
        console.log('position', attrs.position);
      }
    };
  }
]);
function MyCtrl($scope) {
  $scope.positions = [[39, -90],[38, -91]];
}
</script>
</head>

<body ng-controller="MyCtrl">
  <map zoom="12" center="[39, -90]">
    <marker ng-repeat='p in positions' position="{{ p }}"></marker>
  </map>
</body>
</html>

这是在这里演示的,http://plnkr.co/edit/IN237QwEdNkdzpDaX70z?p=preview 错误是,

TypeError: Cannot call method 'insertBefore' of null
    at http://code.angularjs.org/1.2.5/angular.js:2760:14
    at forEach (http://code.angularjs.org/1.2.5/angular.js:303:18)
    at forEach.after (http://code.angularjs.org/1.2.5/angular.js:2759:5)
    at Object.JQLite.(anonymous function) [as after] (http://code.angularjs.org/1.2.5/angular.js:2825:17)
    at Object.enter (http://code.angularjs.org/1.2.5/angular.js:3906:17)
    at http://code.angularjs.org/1.2.5/angular.js:19048:26
    at publicLinkFn (http://code.angularjs.org/1.2.5/angular.js:5483:29)
    at boundTranscludeFn (http://code.angularjs.org/1.2.5/angular.js:5595:21)
    at controllersBoundTransclude (http://code.angularjs.org/1.2.5/angular.js:6189:18)
    at ngRepeatAction (http://code.angularjs.org/1.2.5/angular.js:19046:15) 

单独使用标记指令效果很好。
http://plnkr.co/edit/4i8Rtvk3Qu1U8JRLRAal?p=preview

我认为当父指令操作 DOM 时会出现问题。 但是,由于我们使用的是指令,它必须操作 dom。

任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs ng-repeat angularjs-google-maps


    【解决方案1】:

    问题是您正在用

    替换地图(标记)的内容
    element.html("this will be a map");
    

    如果您尝试追加它,它将毫无问题地工作。

    element.append("this will be a map");
    

    Here is a JSBin

    【讨论】:

    • 谢谢,就这么简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2013-02-26
    相关资源
    最近更新 更多