angularjs - 在(一个?)data-ng-init 中声明两个对象字面量并将它们绑定(bind)到不同的 View

标签 angularjs angularjs-directive angularjs-scope

我正在尝试创建两个不同的对象文字并将它们绑定(bind)到不同的 View ( <table> s)。但是,我不知道该怎么做。我尝试了以下方法,我在一个 data-ng-init 中声明了两个对象文字的父容器(div)。我也试过有两个不同的data-ng-init该 div 的指令并在每个指令中都有一个对象字面量。然而,这两种方法都不起作用,我得到了错误(如果有人想看到它们,会发布)。

我尝试过的示例:

<div id="recipes" data-ng-init=" 
  dessertsdrinks = [
  {name: 'Apple Pie Popcorn',  url: 'pdfs/recipes/desserts_and_drinks/Apple Pie Popcorn.pdf'},  
  {name: 'Zucchini Muffins',  url: 'pdfs/recipes/Zucchini Muffins.pdf'} 
  ];

  maineats = [ 
  {name: 'Autumn Enchilada Casserole',  url: 'pdfs/recipes/Autumn Enchilada    Casserole.pdf'},
  {name: 'Build your own Taco',  url: 'pdfs/recipes/Build your own Taco.pdf'},]
  ">

  <table id="dessertsdrinks">
    <th>Desserts and Drinks</th>
        <tr data-ng-repeat="recipe in dessertsdrinks | filter:recipesearch | orderBy:'name'">
        <td><a href="{{ recipe.url }}"> {{ recipe.name }} </a></td>
        </tr>
   </table>

<table id="maineats">
        <th>Main Eats</th>
            <tr data-ng-repeat="recipe in maineats | filter:recipesearch | orderBy:'name'">
            <td><a href="{{ recipe.url }}"> {{ recipe.name }} </a></td>
            </tr>
       </table>
 </div>

当我只有一个对象文字和一个 data-ng-init它完美地工作。
但是我怎么能用两个不同的列表来做到这一点呢?有没有更好的办法?

例如,我可以有一个 Controller 将对象字面量绑定(bind)到 $scope基于 View (表)id标签什么的?像这样:

伪代码
function recipeController(){
     if $scope id == "desertsdrinks" {
          $scope.recipes = [{.. dessert and drink recipe obj literal ..}];
     } else if $scope id == "maineats" {
          $scope.recipes =[{.. main eats recipe obj literal..}];
     }
 }

最佳答案

只需在 Controller 内移动对象即可:

$scope.dessertsdrinks = [
  {name: 'Apple Pie Popcorn',  url: 'pdfs/recipes/desserts_and_drinks/Apple Pie Popcorn.pdf'},  
  {name: 'Zucchini Muffins',  url: 'pdfs/recipes/Zucchini Muffins.pdf'} 
];

$scope.maineats = [ 
  {name: 'Autumn Enchilada Casserole',  url: 'pdfs/recipes/Autumn Enchilada    Casserole.pdf'},
  {name: 'Build your own Taco',  url: 'pdfs/recipes/Build your own Taco.pdf'}
]

无需更改在 html 中访问它们的方式。

关于angularjs - 在(一个?)data-ng-init 中声明两个对象字面量并将它们绑定(bind)到不同的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17850212/

相关文章:

javascript - angularJS UI选项卡打印选项卡中选定的内容

javascript - 如何防止 Angular 方法多次触发?

angularjs - 可以使用$$ prevSibling在 'transcluded'指令中访问作用域数据吗?

javascript - 如何在 Directive Link 函数中为变量添加 TemplateURL?

php - 请求为空 laravel ajax 多张图片

javascript - $location 不会在第一次 ng-click 回调时导航

javascript - 使用 angular 指令和 jqLit​​e 选择第一个子图像标签

javascript - 带有 $http 请求的 AngularJS 指令(inprog 错误)

两种方式绑定(bind)的 AngularJS 指令 $scope.$watch 不起作用

javascript - 针对常量求值的 Angular 表达式