Angularjs ng-repeat for array无法正常工作

时间:2015-08-10 10:02:35

标签: javascript arrays angularjs

我有通过这个脚本创建的数组:

    $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;
    };

它创建了这样的数组:

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

当我尝试通过ng-repeat ="在项目"中显示它时,没有任何显示,但在调试控制台中有大量的值。我哪里做错了? 我在选择中使用它:

<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

2 个答案:

答案 0 :(得分:0)

据我说,angular不知道对$ scope.Projects所做的更改。因此,您应该在申请中致电$scope.bindModel。 尝试使用timeout将你的代码包装在$ scope中。$ apply。

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

希望这会有所帮助。

答案 1 :(得分:0)

我可以给你一个暗示,你可以从哪里得到解决你的重复问题的想法:

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.");
    };

}

这里我使用了一个帮助加载数组的按钮,然后在数组中应用html ng-repeat来显示数据。您可以按需加载数组。