当我使用常量时,ng-repeat不起作用

时间:2017-01-18 18:10:19

标签: javascript angularjs angularjs-ng-repeat constants

我是AngularJS的新人。

我必须从常量制作下拉菜单。 这是我的代码:

.constant('COLORS',
    [
        {red: '#ff0000'},
        {green: '#00ff00'},
        {blue: '#0000ff'}
    ]
).directive('colorSetter', ['COLORS', function (COLORS) {
    return {
        scope: {
            user: "="
        },
        restrict: 'E',
        // templateUrl: 'colorSetterDirective.html'
        template: '<select name="mySelect" ng-model="colorModel">' +
        '<option ng-repeat="(key,value) in COLORS">{{c.key}} -  {{c.value}}</option>' +
        '</select>'
    }

然后,它会创建下拉菜单,但没有任何显示。它是空的。 我尝试了一切,但它不会工作。我也使用了那条线,但仍然无法工作:

<option ng-repeat="c in COLORS">{{c}}</option>

PIC: empty selectors

的index.html:

....
<td><color-setter ng-model="colors" user="x"></color-setter></td>

谢谢你们!

编辑: app.js

var app = angular.module("testProject", ['ui.router', 'ngAnimate', 'ngSanitize'])
.service('userService', function ($http) {
    this.getUsers = function () {
        return $http.get('users.json');
    };
})
.controller('testProjectCtrl',function ($scope, userService, COLORS) {
    function GetAllUsers() {
        var getUsersData = userService.getUsers();

        getUsersData.then(function (user) {
            $scope.users = user.data;
        }, function () {
            alert('Error in getting user records');
        });
    }

    function init() {
        $scope.sortType = "username";
        $scope.sortReverse = false;
        $scope.limitNumber = 10;
        $scope.colors = COLORS;

    }

    $scope.setDb = function (darab) {
        $scope.limitNumber = darab;
    }
    init();
    GetAllUsers();

}).constant('COLORS',
    [
        {red: '#ff0000'},
        {green: '#00ff00'},
        {blue: '#0000ff'}
    ]
).directive('colorSetter', ['COLORS', function (COLORS) {
    return {
        scope: {
            user: "="
        },
        restrict: 'E',
        // templateUrl: 'colorSetterDirective.html'
        template: '<select name="mySelect" ng-model="colorModel">' +
        '<option ng-repeat="c in COLORS">{{c}}</option>' +
        '</select>'
    }


}]);

1 个答案:

答案 0 :(得分:0)

您必须在控制器$ scope

中注入常量
.directive('colorSetter', ['COLORS', function (COLORS) {
    return {
        scope: {
            user: "="
        },
        restrict: 'E',
        templateUrl: 'colorSetterDirective.html',
        controller:function($scope){
            $scope.colors = COLORS;
        }
    }
}]);

colorSetterDirective.html:

<select name="mySelect" ng-model="colorModel">
    <option ng-repeat="c in colors">{{c}}</option>
</select>