Passing asynchronously obtained data to a directive

后端 未结 2 1238
粉色の甜心
粉色の甜心 2020-12-18 08:52

I currently have an AngularJS controller that is basically getting some JSON asynchronously through a $http.get() call, then linking t

相关标签:
2条回答
  • 2020-12-18 09:12

    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>
    
    0 讨论(0)
  • 2020-12-18 09:14

    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

    0 讨论(0)
提交回复
热议问题