当数据来自服务器时,未显示特定值

时间:2017-07-02 14:06:09

标签: angularjs

我有一个下拉列表: -

<label>User Names:</label>
<select ng-options="c as c.User for c in userList"
    ng-model="selectedUser" id="search3">
</select>

此下拉列表中的数据来自API。我的指令代码: -

(function () {
    'use strict';
    angular.module('myApp.components')
        .directive('info', info);

    info.$inject = ['$http', '$timeout','ApiServices'];

    function info($http, $timeout, ApiServices) {
        return {
            restrict: 'EA',
            scope: {

            },
            link: function (scope, el, attrs) {
                scope.newinfo = {};

                $('#info').on('hide.bs.modal', function () {
                    scope.newinfo = {};
                });

                $('#info').on('shown.bs.modal', function () {  
                    scope.selectedUser = "EVAN";

    scope.getAllUsersName = function(){
        scope.userList = [];
        ApiServices.getAllUsersName().then(function (response) {
            scope.userList = response.data;//the data is an array of objects
        });
    }

    scope.getAllUsersName();


            //Link function ends below
            },
            templateUrl: 'js/folder/info.html'
        };
    }

})();

有一个用户名: - EVAN。我希望每当页面加载并在选择下拉列表中显示时都会选择此用户。我尝试过多种方式: -

ng-init="selectedUser = 'EVAN'"
ng-value="selectedUser = 'EVAN'"
scope.selectedUser = scope.userList[23].User
scope.selectedUser = "EVAN";Placed it inside the `scope.getAllUsersName` function and outside it too. 

该值分配给ng-model =&#34; selectedUser&#34;。但未在下拉列表中显示。任何人都可以告诉我为什么当页面加载时它没有显示为选中状态?

1 个答案:

答案 0 :(得分:0)

Angular directives具有与之关联的范围。默认情况下,除非明确设置,否则指令不会创建自己的范围。他们使用父母范围。大多数时候它是controller's scope。 您可以使用scope:true更改此默认范围,如下所示:

return {
        restrict: 'EA',
        scope:true,
        link: function (scope, el, attrs) {
          //your processing logic
        }
      }

如果您的指令想与控制器通信,您也可以使用isolated scope

在您的情况下,您应该将选定的用户指定为:

scope.selectedUser = scope.userList[0]; //say "EVAN" at first position

此外,您应该在以下视图中添加您的指令:

<select info="" ng-options="c as c.User for c in userList"
ng-model="selectedUser" id="search3">

我希望这会对你有所帮助!!