简体   繁体   中英

Dynamically changing content with AngularJS directive, factory, and ng-repeat

I am working on a widget that will dynamically change its content whenever I click a corresponding button. I have been spending a ton of hours to figure this out but I couldn't.

I have stored all the data that is provided with angular factory. What I'd like to achieve is whenever I click a button, it will fire an event to grab another property, which is also an another data set, in the factory data. And these will be displayed in the content box with ng-repeat.

I will attach my sample coding below for your information. Please leave any advice or any concepts that will help me understand and figure this out further. Thank you for your time!

//index.html
<div directive>
 <div class='buttons'>
   <p>Button A</p>
   <p>Button B</p>
   <p>Button C</p>
 </div>
 <div>
  <a ng-repeat='a in data'>{{a.title}} {{a.author}}</a>
 </div>
</div>
//app.js
app.directive('directive', ['factoryData', function(factoryData) {
 return {
  restrict: 'A',
  link: function ($scope, ele, attrs) {
   $scope.data = factoryData.firstProp;
   var btns = $(ele).find('p');
   p.on('click', function () {
    $scope.data = factoryData.secondProp;
    ...
    ...
   });
  },
 };
}]);

You need to use $apply in your directive as you are trying to bind the new data to scope out of the angular context.

app.directive('directive', ['factoryData', function(factoryData) {
 return {
  restrict: 'A',
  link: function ($scope, ele, attrs) {
   $scope.data = factoryData.firstProp;
   var btns = $(ele).find('p');
   p.on('click', function () {
    $scope.$apply(function() { // use $apply to set the data..in scope
    $scope.data = factoryData.secondProp;
     });
    ...
    ...
   });
  },
 };
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM