以编程方式设置下拉列表的值

时间:2015-12-28 12:45:05

标签: javascript angularjs

我有一个指令,我想更改点击事件的值。这是触发click事件的控制器(我删除了所有不相关的代码):

(function () {

    "use strict";

    //getting the existing module
    angular.module("app")
        .controller("teamsController", teamsController);

    //inject http service
    function teamsController($scope, $http, divisionService, $rootScope) {

        $scope.divisions = divisionService.all();

        var vm = this;

        vm.teams = [];

        vm.newTeam = {};

        vm.editTeam = function (team) {

            $rootScope.$broadcast('someEvent', [team.division]);
}

以下是捕获事件的地方:

(function () {

    "use strict";

    //getting the existing module
    angular.module("app")
        .controller("divisionsController", divisionsController)
        .directive("divisionDropdown", divisionDropdown);

    //inject http service
    function divisionsController($http, $scope, divisionService, $rootScope) {

        $scope.divisions = divisionService.all();

        $rootScope.$on('someEvent', function (event, selectedDiv) {
            alert(selectedDiv);
            $rootScope.selectedDivision = selectedDiv;
        });
    };

    function divisionDropdown() {
        return {
            restrict: "E",
            scope: false,
            controller: "divisionsController",
            template: "<select class='form-control' ng-model='selectedDivision' ng-options='division.divisionName for division in divisions' required>\
                                <option style='display:none' value=''>{{'Select'}}</option>\
                            </select>"
        };
    }
})();

这是divisionService,我用它来填充下拉列表:

app.factory("divisionService", function ($http) {

        var divisions = [];

        var errorMessage = "";
        var isBusy = true;

        //matched to verb, returns promise
        $http.get('http://localhost:33201/api/Divisions')
            .then(function (response) {
                //first parameter is on success
                //copy response.data to vm.divisions (could alternatively use a foreach)
                angular.copy(response.data, divisions);
            }, function (error) {
                //second parameter is on failure
                errorMessage = "Failed to load data: " + error;
            })
            .finally(function () {
                isBusy = false;
            });

        return {
            all: function () {
                return divisions;
            },
            first: function () {
                return divisions[0];
            }
        };
    });

但是我无法在下拉列表中获取selectedDivision以更改click事件。谁能告诉我如何引用它并重置它?我对Angular中的作用域并不熟悉所以我对$ scope和$ rootScope的使用可能就是问题所在。

0 个答案:

没有答案