Angularjs - Custom directive cannot access controller scope -
i building single page app angular js. problem custom directive myslider cannot access scope of controllers assign template. there way solve problem? here files
index.html
<script src="js/dishesapp.js"></script> <div ng-view></div>
partials/dishestemplate.html
<div my-slider></div>
directives/slider.html
<div id="dishsliderholder"> <ul class="bxslider"> <li class="dishdetails" ng-repeat="dish in dishes"> <div class="item"> <div class="title">{{dish.name}}</div> <div class="description">{{dish.description}}</div> </div> </li> </ul> </div>
dishesapp.js
var dishesapp = angular.module('dishesapp', ['ngroute']); dishesapp.config(function ($routeprovider) { $routeprovider .when('/', {templateurl: 'partials/default.html'}) .when('/noodles', {templateurl: 'partials/dishtemplate.html', controller: 'noodlesctrl'}) .when('/rolls', {templateurl: 'partials/dishtemplate.html', controller: 'rollsctrl'}) .when('/pancakes', {templateurl: 'partials/dishtemplate.html', controller: 'pancakesctrl'}) .when('/rice', {templateurl: 'partials/dishtemplate.html', controller: 'ricectrl'}) .when('/familystyle', {templateurl: 'partials/dishtemplate.html', controller: 'familystylectrl'}) .when('/others', {templateurl: 'partials/dishtemplate.html', controller: 'othersctrl'}) .otherwise({redirectto: '/'}); }); dishesapp.controller('noodlesctrl', function ($scope, $http) { $scope.mycategory = "noodles"; $http.get("http://www.blabla.com/data/dishes.php").success(function (response) { $scope.dishes = response.records; }); }); dishesapp.controller('rollsctrl', function ($scope, $http) { $scope.mycategory = "rolls"; $http.get("http://www.blabla.com/data/dishes.php").success(function (response) { $scope.dishes = response.records; }); }); …………….. dishesapp.directive('myslider', function() { return { restrict: 'a', templateurl: 'directives/slider.html', link: function (scope, element, attrs) { angular.element( document.queryselector('.bxslider')).bxslider(); angular.element( document.queryselector('#dishsliderholder')).css("background-size", getsliderholderbackgroundsize()); } }; });
i figured out problem. slider object called before dom finish rendering slider shows nothing. use $timeout call slider post render. here how did it
dishesapp.directive('myslider', function ($timeout) { return { restrict: 'a', replace: true, templateurl: 'directives/slider.html', link: function (scope, element, attrs) { $timeout(function () { angular.element(document.queryselector('.bxslider')).bxslider(); angular.element(document.queryselector('#dishsliderholder')).css("background-size", getsliderholderbackgroundsize()); }); } };
});
Comments
Post a Comment