javascript - 提供 AngularJS Controller 数据

标签 javascript angularjs

假设有一个 Controller 来操作示波器上的一些数据,那么向 Controller 提供该数据的最佳做法是什么?

例如,如果我有一个项目列表,我可能需要一个 ListController 来操作列表,并需要一个 ItemController 来操作单个项目。但是我如何给每个 ItemController 一个项目来使用呢?

在下面的例子中,doSomethingToItem 将如何访问项目。当嵌套在 ngRepeat 中时,项目是 $scope.item,但在选择 View 中,我们要操作的项目是 $scope.selection。

angular.module('MyApp', [])

    .controller('ListController', function($scope, $http) {

        $scope.list = $http.get(...);

        $scope.selection = null;

    })

    .controller('ItemController', function($scope) {

        $scope.doSomethingToItem = function() {
            ...
        };

    })


<div ng-controller="ListController">
    <div ng-repeat="item in list" ng-click="selection = item">
        <div ng-controller="ItemController">
            <button ng-click="doSomethingToItem()">Do Something</button>
        </div>
    </div>
    <div ng-show="selection"
        <div ng-controller="ItemController">
            <button ng-click="doSomethingToItem()">Do Something</button>
        </div>
    </div>
</div>

这不是常见的结构,还是我思维倒退了?

最佳答案

您应该明白,在您的情况下,Angular 会创建 n+1 个 ItemController。 N 用于项目,1 用于选择部分。

为了更轻松地传递需要处理的对象,您可以将方法签名更改为

doSomethingToItem(item)在 html 中做

<button ng-click="doSomethingToItem(item)">Do Something</button>在这两个地方。

否则对于重复情况 item变量包含您可以在 ItemController 中访问的对象

selection变量包含对选择 Controller 的引用,可以从选择部分下定义的 Controller 实例中引用。

更新:ng-repeat 和 selection 中的表达式会有所不同

<button ng-click="doSomethingToItem(item)">Do Something</button>

 <div ng-show="selection"
        <div ng-controller="ItemController">
            <button ng-click="doSomethingToItem(selection)">Do Something</button>
        </div>
    </div>

关于javascript - 提供 AngularJS Controller 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366359/

相关文章:

javascript - Angular $locationProvider 不改变 .url()

javascript - 如何在新窗口中打开部分 View 并调用打印方法?

javascript - 使用 onClick 事件从 Redux 存储中删除项目时出现问题

javascript [object Object] 到字符串

JavaScript 版本高于 1.5 - 为什么?

javascript - 从外部调用 Controller 功能

javascript - 基本(本地)HTML 不加载图像或 js 但加载 css

Javascript/jQuery .load 将多个文件加载到 div 中

javascript - Sequelize - 更新时如何部分验证?

javascript - Angular ng-show 表达式引用 html 内容