Passing asynchronously obtained data to a directive

拜拜、爱过 提交于 2019-11-29 07:46:01

Move the declaration for the sidebar object in the controller and change the scope binding to =.

mapsDirectives.controller("interactionsController", ["$http", "$timeout",
    function($http, $timeout) {
        var ctrlModel = this;
        ctrlModel.sidebar = {
            pages: []
        };
      /*
      $http.get("data/interactionsPages.json").
          success(function(data) {
          //ctrlModel.sidebar = {};
          ctrlModel.sidebar.pages = data;
       }).
       error(function() {});
      */

      $timeout(function() {
        //ctrlModel.sidebar = {};
        ctrlModel.sidebar.pages = ["one", "two"];
      }, 2000);
    }
]);

mapsDirectives.directive('mmSidebar', [function() {
    return {
      restrict: 'E',
      scope: {
        pages: '='
      },
      controller: function() {},
      link: function(scope, element, attrs, ctrl) {
        scope.$watch("pages", function(val) {
          scope.firstPage = 0;
          scope.lastPage = scope.pages.length - 1;
          scope.activePage = 0;
        });
      },
      templateUrl: 'sidebar.html'
    };
}]);

Then match the directive name and drop the braces.

<mm-sidebar pages='interactionsCtrl.sidebar.pages'>
</mm-sidebar>

Here's a working example: http://plnkr.co/edit/VP79w4vL5xiifEWqAUGI

The problem appears to be your html markup.

In your controller you have specified the ctrlModel is equal to this.

In your html markup you have declared the same this to be named interactionsController.
So tacking on ctrlModel to interactionsController is incorrect.

<body>
  <div ng-controller='interactionsController as interactionsCtrl'>
    <!-- remove this -->
    <mm-sidebar pages='{{interactionsCtrl.ctrlModel.sidebar.pages}}'>

    <!-- replace with this -->
    <mm-sidebar pages='{{interactionsCtrl.sidebar.pages}}'>

    </mm-sidebar>
  </div>
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!