Angular Unpacking

Suppose I have this controller:

myApp.controller('testCtrl', function ($scope) {
    $scope.cars = [
        { carId: '1', carModel: 'BMW', carOwner: 'Nader' },
        { carId: '2', carModel: 'Mercedes', carOwner: 'Hisham' },
        { carId: '3', carModel: 'Opel', carOwner: 'Saad' }
    ];
});

and this HTML:

<select ng-options="car as car.carModel for car in cars" ng-model="car"></select>
<br />
<label> Car ID </label> <input type="text" ng-model="car.carId" />
<br />
<label> Car Model </label> <input type="text" ng-model="car.carModel" />
<br />
<label> Car Owner </label> <input type="text" ng-model="car.carOwner" />

When the user selects a car, he should automatically bind the values ​​of the selected car to the text fields that already occur in this case. However, when I change the value in the text box for carModel, the name carModelin the drop-down list changes.

How can I change the input for carModelwithout changing the value in the dropdown menu? Please note that I want to bind the information of the selected vehicle to the text fields whenever the user selects a different value from the drop-down list.


Use case

, , , , , , , , - .

+4
3

angular.copy :

JavaScript: callTest testCtrl

$scope.cars = [ ... ];

$scope.callTest = function(objCar) {
  console.log(objCar);
  $scope.carModel = angular.copy(objCar); // this carModel is used in the html
};

HTML:

<select ng-change="callTest(car)" ng-options="car as car.carModel for car in cars" ng-model="car"></select>
<br />
<label> Car ID </label>
<input type="text" ng-model="carModel.carId" />
<br />
<label> Car Model </label>
<input type="text" ng-model="carModel.carModel" />
<br />
<label> Car Owner </label>
<input type="text" ng-model="carModel.carOwner" />

ng-change event callTest() .

Plunker

+4

, , :

  • ng-change <select> car angular.copy()
  • ng-model="carCopy.propName"
  • angular.extend(), car
+2

. . . select , Object .

template.html

<br />
<label> Car ID </label> <input type="text" ng-model="carId" />
<br />
<label> Car Model </label> <input type="text" ng-model="carModel" />
<br />
<label> Car Owner </label> <input type="text" ng-model="carOwner" />

html view

 <select ng-options="car as car.carModel for car in cars" ng-model="car"></select>
 <ca car-id="{{car.carId}}" car-model="{{car.carModel}}" car-owner="{{car.carOwner}}"></ca>

, .

.directive('ca', function() {
  return {
    scope:{
            carId:'@',
            carModel:'@',
            carOwner:'@'
        },
    templateUrl: 'template.html'
  };
});

plunker

Angular 2.0 .

+1

Source: https://habr.com/ru/post/1626754/


All Articles