salamanka44 salamanka44 - 7 days ago 7
AngularJS Question

Binding using ui-select in angular

I wrote a little program using ui-select in angular and it seems that they some "bugs" with the ng model (for me, it have some "strange" behavior) and I couldn't bind the value set in the ng-model from the .js controller.

Here is my html code :

<body ng-controller="mainController">
<p>SelectedName: {{test.selectedContract.name}}</p>
<p>Selected: {{test.selectedContract}}</p>

<ui-select ng-model="test.selectedContract">
<ui-select-match>
{{$select.selected.name}} - {{$select.selected.value}}
</ui-select-match>

<ui-select-choices repeat="contract in (contracts | filter: {name: $select.search} ) track by contract.name">
{{contract.name}} - {{contract.value}}
</ui-select-choices>
</ui-select>

<p> selectedFromJS = {{mySelected}} </p>
<p> selectedNameFromJS = {{mySelected2}} </p>


The two variables Selected and SelectedName seems correct and I could view the selectecContract in html by if I wanted to manipulate it in my controller, I failed.

Here is the binding in my controller :

$scope.test = {};
$scope.test.selectedContract = {};

$scope.mySelected = $scope.test.selectedContract
$scope.mySelected2 = $scope.test.selectedContract.name


Finally, here is my code : http://plnkr.co/edit/WxMXD8yptwfsr80hJJWJ?p=preview

As you can see, the last two variables selectedFromJS and selectedNameFromJS didn't work and didn't show anything.

Can you please show me how can I do correctly the binding and how can I manipulate the selected item in my controller.

Thanks !

Answer

The controller is loaded once. Data is bing to test.selectedContract. This is how you create your own watches. $watch service helps you to run some code when some value attached to the $scope has changed.

Please Try:

  $scope.$watch('test.selectedContract', function() {
       $scope.mySelected = $scope.test.selectedContract
       $scope.mySelected2 = $scope.test.selectedContract.name
  });
Comments