البرمجة

كيفية تعيين قيمة في عنصر select باستخدام AngularJS

To set a value in a select element based on an object’s ID in AngularJS, you can use the ng-model directive along with ng-options to bind the selected value. Here’s how you can do it:

First, ensure that the ng-model directive is bound to a variable that represents the selected ID. For example:

html
<select class="form-control" ng-model="selectedOperadoraId" ng-options="operadoraTemp.codigo as operadoraTemp.nome + ' (' + (operadoraTemp.preco | currency) +')' for operadoraTemp in operadoras | orderBy:'nome'"> <option value="">option> select>

In this example, selectedOperadoraId will hold the ID of the selected phone company (operadora).

Next, in your controller or directive, you can set the initial value of selectedOperadoraId to the ID of the current contact’s phone company. For example, if contato.operadora.codigo represents the ID of the phone company for the current contact:

javascript
$scope.selectedOperadoraId = contato.operadora.codigo;

This will preselect the corresponding option in the select element.

Finally, to dynamically update the contact’s phone company when the user selects a different option, you can watch for changes to selectedOperadoraId and update contato.operadora.codigo accordingly:

javascript
$scope.$watch('selectedOperadoraId', function(newVal, oldVal) { if (newVal !== oldVal) { // Find the selected phone company by ID var selectedOperadora = $scope.operadoras.find(function(operadora) { return operadora.codigo === newVal; }); // Update the contact's phone company contato.operadora = selectedOperadora; } });

This code assumes that operadoras is an array containing all phone companies and that contato is the current contact object being edited.

المزيد من المعلومات

بالطبع! إليك المزيد من المعلومات:

في AngularJS، يمكنك استخدام الديركتيف ng-model مع الديركتيف ng-options لربط قيمة محددة في عنصر select بنموذج البيانات. عندما يتم اختيار خيار معين، سيقوم AngularJS بتحديث القيمة المرتبطة بـ ng-model بقيمة الخيار المحدد.

في الكود الذي قدمته، يمكنك استخدام ng-model="selectedOperadoraId" لربط القيمة المحددة في الـ select بمتغير يحمل ID الشركة المحددة. ويمكنك استخدام ng-options لإنشاء خيارات الـ select بناءً على قائمة الشركات الموجودة في operadoras.

عند تغيير القيمة المحددة في الـ select (selectedOperadoraId في هذه الحالة)، يمكنك استخدام دالة الـ $watch لمراقبة التغييرات وتحديث بيانات الاتصال (contato) بناءً على القيمة الجديدة.

زر الذهاب إلى الأعلى