Question

I am new to angularjs

Html file:

<div class='col-md-2 searchdisplay-col1' ng-controller="amenitiesController" style="margin-top:20px">
    <h4>Amenities</h4>
    <label ng-repeat="facilityName in facilityNames" style="display:block;">
        <input
            type="checkbox"
            name="{{facilityName.name}}"
            value="{{facilityName.id}}"
            ng-checked=""
            ng-click="lodgeFilter($event,facilityName.id)"
        /> {{facilityName.name}}
    </label>
</div>

Controller:

App.controller('amenitiesController',['$scope','$http', function($scope,$http){

    $scope.facilityNames = []; // Initialize array for checkboxes

    $http({method: 'GET', url: "/api/facilities.json"})
        .success(function(data, status) {

            $.each(data, function(i,f) {
                $scope.facilityNames.push({ name: f.facility.name, id: f.facility.id });
            });

        })
        .error(function(data, status) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });

    $scope.lodgeFilter = function($event, id) {
        html = "";
        $http({method: 'GET', url: "/api/location/"+location_id+".json"})
            .success(function(data, status) {
                //Some Code     
            })
            .error(function(data, status) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
           });
        $("#results-display").html(html);
    }
}]);

Sample Json

[
    {
        "facility": {
            "id": 1,
            "name": "Internet"
        }
    },
    {
        "facility": {
            "id": 2,
            "name": "Bar"
        }
    }
]

Now when I click on checkbox, I get expected result.But when I uncheck it remains in same state, how do I make it to go to initial state?

Was it helpful?

Solution

You can use "ng-model" as follows (even when the key "model" does not exist in the object):

HTML:

<label ng-repeat="value in values">
    <input 
        type="checkbox"
        ng-model="value.model"
        ng-change="someFunc($event, value.model, value.id)"
    /> {{value.id}}
</label>

Controller:

function MainCtrl ($scope) {
    $scope.values = [
        {id:1},
        {id:2},
        {id:3}
    ];

    $scope.someFunc = function (event, active, id) {
        if ( active ) {
            alert('Change detected: '+id);
            // HTTP request code
        }
        // Some code
    };
}

DEMO: http://jsfiddle.net/Chofoteddy/8bzbD/

OTHER TIPS

You might need to add ng-true-value and ng-false-value for your custom values to checkbox.

Have a look into this link Checkbox

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top