gpt4 book ai didi

javascript - 如何访问 Select2 "change"处理程序中的 Angular 范围?

转载 作者:行者123 更新时间:2023-11-30 08:46:00 25 4
gpt4 key购买 nike

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

enter image description here

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

笨蛋: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() 但它只是看起来对我来说很丑

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

最佳答案

您可以像@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%;'>"
}
});

关于javascript - 如何访问 Select2 "change"处理程序中的 Angular 范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21996377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com