更改事件不会在angular指令中触发

时间:2014-02-19 08:49:21

标签: angularjs angularjs-directive

我正在写一个角度指令。这是代码:

'use strict';
app.directive('mcategory', function (MainCategory, $rootScope) {
return {
    restrict: 'E',
    replace: true,
    template: '<select data-ng-model="selectedMainCategory" data-ng-options="mainCategory.mainCategoryId as mainCategory.mainCategoryName ' +
        'for mainCategory in mainCategories" data-ng-change="mainCategoryChanged()"></select>',
    link: function(scope, element, attr, controller) {
        var elm = angular.element(element);
        elm.attr('id', attr['id']);
        elm.attr('name', attr['name']);
        elm.attr('class', attr['class']);
        MainCategory.get().then(function (mainCategories) {
            scope.mainCategories = mainCategories;
        });
        scope.selectedMainCategory = false;
        scope.mainCategoryChanged = function () {
            if (!scope.selectedMainCategory) {
                return;
            }                
            $rootScope.$broadcast("mainCategoryChanged", { mainCategory: scope.selectedMainCategory });
        };
    }
};
})

MainCategory是一项服务,它运作正常。

问题是当用户在select元素中选择另一个类别时,selectedMainCategory始终为undefinedmainCategoryChanged()事件未被触发。我想我犯了一个愚蠢的错误,但是超过2个小时我无法解决问题。提前感谢任何帮助。

更新 这是服务:

'use strict';
app.factory('MainCategory', function ($http, $q) {
    return {
        get: function() {
            var deferred = $q.defer();
            $http.get('/MainCategory/GetMainCategories').success(deferred.resolve).error(deferred.reject    );            
            return deferred.promise;            
        }
    };
})

当我在浏览器中'/MainCategory/GetMainCategories' url时,我会以正确的json格式获取所有类别。

0 个答案:

没有答案