javascript - 将值存储在指令中以备后用

标签 javascript angularjs angularjs-ng-repeat

我想在 ngRepeat 中保存一个对象,以便我可以在其子对象中使用该对象,如以下代码所示:

<div ng-repeat="bar in foo.bar> 
    <div ng-repeat="qux in baz.qux" myvalue="{'item1':foo.var1, 'item2':qux.var2}">
        <div ng-click="myFirstFunction(myvalue)"></div>
        <div ng-click="mySecondFunction(myvalue)"></div>
    </div 
</div

我要生成然后使用的对象相当大,我不想为每个 ngClick 指令重复定义它。

我考虑过将它保存到范围变量中,但该对象会随着 ngRepeat 的每次迭代而改变。

是否有指令或其他方式可用于存储此值供以后使用?

最佳答案

为避免重复可能很长的变量定义,您可以使用 ngInit指令,其内容将在每次创建相应元素时执行。

<div ng-repeat="bar in foo.bar> 
    <div
        ng-repeat="qux in baz.qux"
        ng-init="myValue = {'item1':foo.var1, 'item2':qux.var2 }"
    >
        <div ng-click="myFirstFunction(myValue)"></div>
        <div ng-click="mySecondFunction(myValue)"></div>
    </div>
</div>

但是,模板中的复杂代码很少是个好主意。按照文档的建议,考虑将您的逻辑移动到 Controller 中:

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

关于javascript - 将值存储在指令中以备后用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917243/

相关文章:

javascript - 服务器无响应时如何处理ajax调用

javascript - 使用 jQuery 换行函数

angularjs - 来自服务的 ionic 模式窗口

templates - AngularJS : Creating a directive that repeats a transcluded template

javascript - AngularJS ng-repeat 过滤功能未正确过滤

angularjs - ng-repeat 中的按钮以更新表单中的输入

javascript - 隐藏错误文本,直到框/按钮被点击

javascript - 我可以使用 Ajax 更改文本框的值吗

javascript - $watch 和 2 个 Controller

javascript - 动态 Angular 表不使用分页进行过滤