从 Angular.js 视图中修改方法中的数据的最佳做法

Best practice for modifying data in a method from the view in Angular.js

本文关键字:数据 最佳 修改 Angular js 视图 方法      更新时间:2023-09-26

我正在编写一个角度应用程序来显示可以使用引导折叠手风琴打开和关闭的报告。我决定向手风琴的报表对象添加一些特定于视图的值,如下所示:

var report = [{
    "testName": "Cool Test",
    "successful": true,
    "openAccordion": "in" //this was added for bootstrap's sake to say whether this test in the report is collapsed or not
}]

我认为这样我就可以更新我的模型,双向数据绑定将为我折叠和解压缩内容。

不过,我现在想做的是,我想添加执行这些操作的按钮。例如,我想要一个按钮,用于将报表中的所有测试设置为"openAccordion":"in"以打开所有测试,另一个按钮将它们设置为"openAccordion":""以关闭所有测试。

我想出我可以编写一个服务,其功能挂在上面,如下所示:

bookApp.factory('report', function() {
    this.getReport = function() {
        [...]
        return report;
    }
    this.setAccordions = function(report, setting) {
        [set all tests to setting's value ...]
    }
    return this;
});

我想我喜欢这样,但是使用ng-click来启动setAccordions功能的最佳方法是什么?我是否必须在ReportCtrl中将该服务函数设置为$scope函数,或者我可以直接从视图中从服务中调用该函数?

可以直接调用工厂函数,但首先控制器必须将其绑定到控制器的作用域:

myApp.controller('Ctrl', function ($scope, report) { 
    $scope.setAccordions = report.setAccordions;
}

然后,您可以使用:

<button ng-click="setAccordions(true)">Set to true </button>