2015-10-19 3 views
0

HTML:Как передать переменные директиве от контроллера?

<div ng-repeat="item in productArr"> 
    {{ item.title }} 
</div> 
<div category-page-navigation current-page='currentPage' category-products-count='productsCount'></div> 

JS:

.controller('categoryController', ['$scope', '$location', '$http', '$q', '$window', '$stateParams', function($scope, $location, $http, $q, $window, $stateParams) { 

     $scope.currentPage = 1; 
     $scope.productsCount = 0;    

     var GET = { 
      getProductData: function() { 
       var defer = $q.defer(); 

       $http.post('services/loadProduct.php', { 
        'id' :1, 
       }).then(function(response) { 
        defer.resolve(response); 
       }, function(response) {    
        defer.resolve([]); 
       });   

       return defer.promise;    
      } 
     }; 

     var getData = { 
      getProduct: function() { 
       var productData = GET.getProductData(); 

       $q.all([productData]).then(
        function(response) { 
         $scope.productArr = response[0].data.products; 
         $scope.productsCount = response[0].data.products.length; 
        });   
      } 
     }; 

     getData.getProduct(); 

    }]) 
    .directive('categoryPageNavigation', function($compile, $parse) { 
     return { 
      scope: { 
       currentPage: '=currentPage', 
       categoryProductsCount: '=categoryProductsCount' 
      }, 
      link: function (scope, element, attrs) { 
       debugger; 
       // Here scope.categoryProductsCount = undefined 
       // ... 
       $scope.$watch(scope.currentPage, function(value) { 
        // ... 
       });        
      } 
     }; 
    }); 

Я стараюсь, чтобы сформировать новый HTML для навигации, чтобы манипулировать HTML я получаю от нг-повтора. В директиве мне нужна текущая страница (от начала = 1) и общее количество элементов из ng-repeat (длина массива), которое я получаю от службы. Как передать переменные в директиву? Сначала мне нужно получить переменные из службы (ajax-запрос или что-то еще), а затем передать переменные (некоторые данные ather) в директиву.

ответ

0

Если я правильно понял, что вы имеете в виду. Вот пример кода, в котором описано, как делиться данными между контроллером и вашей директивой.

Хорошо читать, чтобы понять код ниже: https://docs.angularjs.org/guide/providers

http://codepen.io/chocobowings/full/Xmzxmo/

var app = angular.module('app', []); 
 
//-------------------------------------------------------// 
 
app.factory('Shared', function() { 
 
    return { 
 
    sharedValue: { 
 
     value: '', 
 
    } 
 
    }; 
 
}); 
 
//-------------------------------------------------------// 
 
app.controller('ctrl', function($scope, Shared) { 
 
    $scope.model = Shared.sharedValue; 
 
}); 
 
//-------------------------------------------------------// 
 
app.directive('directive', ['Shared', 
 
    function(Shared) { 
 
    return { 
 
     restrict: 'E', 
 
     link: function(scope) { 
 
     scope.model = Shared.sharedValue; 
 
     }, 
 
     template: '<div><input type="text" ng-model="model.value"/></div>' 
 
    } 
 
    } 
 
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app"> 
 
    Ctrl: 
 
    <div ng-controller="ctrl"> 
 
    <input type="text" ng-model="model.value" /> 
 
    <br/> 
 
    </div> 
 
    Directive: 
 
    <directive value="model.value"></directive> 
 
</div>

+0

Probles является то, что директива выполнить Befor Быстродействие ручкой. Как это исправить? –

+0

Я нахожу решение: http://stackoverflow.com/questions/30504496/angularjs-run-directive-after-success-of-http –

+0

Да, поскольку ваш HTTP-вызов асинхронен, вам придется подождать, пока вы не получите ответ перед обновлением ваша директива. Если вы чувствуете, что ответили на вопрос, пожалуйста, отметьте его как ответ. Благодаря :) –

Смежные вопросы