javascript - Angular Controller 的动态属性

标签 javascript angularjs

我正在尝试根据不同的值动态加载 Controller ,并想知道这样做的实际方法是什么?见下文。

我正在尝试在其所在的 Controller 中检索 data-post-id 属性的值。

假设我在同一页面上有多个 CommentsController div,并且每个 div 都与不同的 data-post-id 关联。

任何帮助将不胜感激。

谢谢。

JS

app.controller("CommentsController", function($scope, $http) {
   $scope.comments = [];
   $scope.load = function() {
      $http.get("https://myapi.com/comments.json", [post_id: post_id])
          .success(function(data) {
              $scope.comments = data;
          });
   };
   // Load the data
   $scope.load();
});

HTML

<div ng-controller="CommentsController as comments" data-post-id="30">
   <div ng-repeat="comment in comments">
      {{ comment.body }} - {{ comment.author }}
   </div>
</div>

最佳答案

这可能发生在您的 angular.module('app').config(function(){

您可以拥有一组 Controller 类型,即 var yourCtlrTypes = ['comments','posts','users'] 然后使用 Angular 的 Controller Provider在该数组的循环内部。您的循环将为数组中的每个名称创建一个 Controller ,每个 Controller 还可以根据数组对 $scopes 和变量进行特殊命名。即 images[x] = {},其中 x 是循环数组中的当前项目。

});

让我知道这是否有意义或者我可以制作一个演示。

关于javascript - Angular Controller 的动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26921286/

相关文章:

javascript - 使用 jQuery 以编程方式触发 'checked' 复选框

javascript - AngularJs - 将参数传递到来自不同 Controller 的对象的绑定(bind)

angularjs - 我可以在 ngIf 语句中使用过滤器吗

Javascript 和 SVG - 使用偏移量移动元素

javascript - 调用FlashExternalInterface方法时出现疯狂 "unexpected token illegal"错误

javascript - Angular 7 共享服务不共享

javascript - 在 node.js 中使用 stripe 实现 ach

javascript - AngularJS : How to avoid - Broadcast event called from app. js 被触发两次?

javascript - 指令的竞争条件

javascript - angularjs 无法加载 jaydata 模块