简体   繁体   中英

Angularjs ng-repeat for array not working

I have array that creates via this script:

    $scope.bindModel = function(data) {
        $scope.model = data;
        $scope.projects = projectNames();
        $scope.$apply($timeout($scope.bindModel(data)));
    };

    /* Function that enumerates the names of the project in the list of model's object*/
    var projectNames = function () {
        var array = [];
        // SOME CODE . . .
        return array;
    };

And it's creates array like this:

$scope.projects = ["first project", "second project", "third project"];

And when I try to show it on page via ng-repeat="project in projects", nothing not shows, but in debug console massive have values. Where did I go wrong? I use this in select:

<select class="chzn-border" style="width:98%">
     <option disabled selected style='display:none;'>Choose a project...</option>
     <option ng-repeat="project in projects" value="{{project}}">{{project}}</option>
</select>

JSFiddle

According to me angular is unaware of the changes made to $scope.Projects. So you should call $scope.bindModel in apply. Try using timeout which will wrap your code in $scope.$apply.

$timeout($scope.bindModel(data));

Hopefully this will help.

I can give you a hint from where you can get idea to solve your ng-repeat problem:

HTML:

<div ng-app ng-controller="MyController">
    <input type="submit" ng-click="projectNames()" value="submit"></input>
    <select class="chzn-border" style="width:98%">
     <option disabled selected style='display:none;'>Choose a project...</option>
     <option ng-repeat="project in projects" value="{{project}}">{{project}}</option>
</select>

Angular JS:

function MyController($scope) {
  // $scope.bindModel = function(data) {
        //$scope.model = data;
        //$scope.projects = projectNames();
    //alert($scope.projects);
    //};

    $scope.projects = [];
    $scope.projectNames = function () {
        $scope.projects.push(" a is a project.");
        $scope.projects.push(" b is a project.");
        $scope.projects.push(" c is a project.");
    };

}

Here i have used a button that is helping to load the array and then in html ng-repeat is applied on array to show the data. You can load array on load like you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM