使用AngularJS指令、工厂和ng-repeat动态修改内容

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

本文关键字:动态 修改 ng-repeat AngularJS 指令 工厂 使用      更新时间:2023-09-26

我正在制作一个小部件,每当我单击相应的按钮时,它都会动态更改其内容。我已经花了很多时间想弄明白这个问题,但是我还是不明白。

我已经存储了angular factory提供的所有数据。我想要实现的是,每当我单击一个按钮时,它将触发一个事件来获取工厂数据中的另一个属性,这也是另一个数据集。这些将显示在ng-repeat的内容框中。

我将附上我的代码示例如下供您参考。请留下任何建议或任何概念,这将有助于我理解和进一步弄清楚这一点。感谢您的宝贵时间!

//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;
    ...
    ...
   });
  },
 };
}]);

你需要在指令中使用$apply,因为你试图将新数据绑定到angular上下文之外的作用域。

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;
     });
    ...
    ...
   });
  },
 };
}]);