1

I'm writing an angular app to display reports which can open and close with bootstrap collapse accordions. I decided to add some view specific values to my report object for the accordion, like this:

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
}]

I figure that way I can just update my model and the two-way databinding will collapse and uncollapse things for me.

What I want to do now, though, is I want to add buttons that do this stuff. For example, I want a button that sets all the tests in a report to "openAccordion":"in" to open all the tests, and another that sets them to "openAccordion":"" to close all the tests.

I figured out I could write a service that has functions hanging off it like this:

bookApp.factory('report', function() {

    this.getReport = function() {
        [...]
        return report;
    }

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

    return this;

});

I think I like that, but then what's the best way to use an ng-click to kick that setAccordions function off? Do I have to set that service function as a function off my $scope in my ReportCtrl, or can I call that function off the service directly from the view?

4

1 回答 1

1

You can call the factory function directly, but first the controller has to bind it to your controller's scope:

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

Then you can use:

<button ng-click="setAccordions(true)">Set to true </button>
于 2013-11-07T21:40:32.640 回答