Parker Song
Parker Song

Reputation: 151

Error caused when set checkboxes as checked using angularjs

This is the html:

<span ng-repeat="category in categories">
      <label class="checkbox-inline" for="{{category.id}}">
        <input type="checkbox" ng-checked="check(category.id)" ng-click="saveRoleMenu($event,category.id)" name="group" id="{{category.id}}" />
        {{category.name}}
      </label>
</span>

this is my controller:

//get all the menus
authorityService.getMenus().then(function(response) {
    $scope.categories = response.data.data; //get all the menus success
})

//get the user's menus
var roleId = sessionStorage.getItem("roleId");
authorityService.getMenusByRoleId(roleId).then(function(response) {
    $scope.userMenu = response.data.data; //get the user's menu success
})
$scope.saveRoleMenu = function($event, id) {
    var checkbox = $event.target;
    if (checkbox.checked) {
        var roleId = $location.search().id;
        authorityService.saveRoleMenu(roleId, id).then(function(response) {
            if (response.data.code == 0) {
                alert("success!");
            }
        })
    }
}

$scope.check = function(value) {
    //error caused here
    for (var i = 0; i < $scope.userMenu.length; i++) {
        if(value == $scope.userMenu[i].id){
            return true;
        }else{
            return false;
        }
    }
}

I want to set checkbox checked if the value in $scope.userMenu,but in the check function,caused the error "Cannot read property 'length' of undefined",what's the reason about this error?

Upvotes: 0

Views: 50

Answers (2)

Sushant
Sushant

Reputation: 1414

Its because your userMenu are loaded from API and the check function execute before they are loaded.

define the userMenu in top something like this -

$scope.userMenu = [];

This would stop check from throwing errors. Once menu are loaded from API view will re-render with it.

Upvotes: 1

Sarjan Desai
Sarjan Desai

Reputation: 3733

Cannot read property 'length' of undefined

means $scope.userMenu is not defined. Define $scope.userMenu before assigning value to it.

$scope.userMenu = [];
var roleId = sessionStorage.getItem("roleId");

Upvotes: 2

Related Questions