1

我真的很想知道如何为正确的对象设置正确的属性。

在此处输入图像描述

目前在“更改”事件处理程序中,我不知道我所处的范围。实际上我不知道应该更新哪个位置。

Plunker:http ://plnkr.co/edit/T4aBzND7VV2gCkui0I7P?p=preview

代码亮点

app.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.locations = ['Paris', 'London'];
}]);

app.directive('timezone', function(timezones) {
    var _updateSetting = function(e) {
        console.log(e.target.value);
        // How do I update objects in my scope?
        // (cannot access here)
    };
    return {
        restrict: 'E',

        link: function(scope, el, attrs) {
            el.select2( { data: timezones.get() } ).on("change", _updateSetting);
        },

        template : "<input type='hidden' class='timezoneSelector' style='width: 100%;'>"
    }
});

app.factory('timezones', function() {
    var timezones = ["Europe/London", "Europe/Paris"];
    var timezonesSelect = timezones.map(function(obj) { return {id: obj, text: obj }; } ); 
    // preparing data so it is ready to use for select2
    return {
        get : function() { return timezonesSelect; }
    }
});

注意:我不想使用https://github.com/angular-ui/ui-select2 我想更接近我的代码,控制自己:)

注意: Select2 构造了一些屏幕外的 div,我可能会查找$(e.target).parent().text(),但它对我来说看起来很难看

如果您对如何以“角度方式”正确执行此操作有任何建议 - 请在答案/评论中告诉我:)

4

2 回答 2

4

您可以通过将其作为参数传递来访问范围,如@urban_racoons 的回答。然而,当你在 Angular 之外使用事件时,你必须让它知道你已经通过使用$apply.

app.directive('timezone', function(timezones) {
        var _updateSetting = function(scope, e) {
            console.log(e.target.value);
            // now you can update scope
        };

        return {
            restrict: 'E',

            link: function(scope, el, attrs) {
                el.select2( { data: timezones.get() } ).on("change", function(e) {
                  scope.$apply( function() {
                    _updateSetting(scope, e);
                  });
                });
            },

            template : "<input type='hidden' class='timezoneSelector' style='width: 100%;'>"
        }
    });
于 2014-02-24T20:50:58.077 回答
1

我不确定这是否是我最喜欢的方式,但它应该适用于您感兴趣的内容:

app.directive('timezone', function(timezones) {
    var _updateSetting = function(locations) {
        console.log(locations);

    };

    return {
        restrict: 'E',

        link: function(scope, el, attrs) {
            el.select2( { data: timezones.get() } ).on("change", function() {
              _updateSetting(scope.locations);
            });
        },

        template : "<input type='hidden' class='timezoneSelector' style='width: 100%;'>"
    }
});
于 2014-02-24T19:15:27.200 回答