【问题标题】:ng-repeat not working when i use constant当我使用常量时,ng-repeat 不起作用
【发布时间】:2017-01-18 18:10:19
【问题描述】:

我是 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>

图片: 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>'
    }


}]);

【问题讨论】:

  • 您必须将COLORS 常量绑定到控制器$scope 才能在视图级别访问它..
  • 我编辑了代码,完整的app.js文件,请检查。谢谢Pankaj

标签: javascript angularjs angularjs-ng-repeat constants


【解决方案1】:

你必须在控制器 $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>

【讨论】:

  • 感谢 DevSullo,现在可以使用了。我不知道,我需要在控制器中注入颜色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多