angularjs - Set ng select dropdown model to null when model does not exist in ng-options -


Assume that I define the following drop down in the UI:

  & lt ; Ng-model = "selected item" ng-options = "items as items. Item items from item items to item.id" & gt; & Lt; Option value = "" & gt; Please select ... & lt; / Options & gt; & Lt; / Select & gt;   $ scope.items = [{name: 'item1', id: 0}, {name: 'item2 ', Id: 1}]; $ Scope.selectedItem;   

If I set the $ scope.selectedItem or the item is present in the value then the item is present in the array {name: 'item1', Id: 1} then angular preselects 'item1' which is in line with expectation.

But if I have a bogus item that does not exist in the item array like $ scope.selectedItem = {name: 'item 6', id: 6} then angle preselects 'Please select ...' which is expected in the UI, but the model still remains {name: 'item 6', id: 6} .

For example, with a bogus item, model {name: 'item 6', id: 6} ?

Instead of $ scope.selectedItem to null in my case, the $ scope.selectedItem object is being saved in the database so that Filled in the future, I can not guarantee that the object will be present in the $ scope.items array. If the object is no longer present in Array, then I would like to set the model rather than retaining the stale object.

The obvious solution would be whether the object exists in array and if it does not manually set $ scope.selected = null in the controller, but wants to see if There was no easy or cleaner option.

Solution:

Optimized to use an instruction:

 . Directive ('checker tap', function) {return {link: function (scope, element, attrs) {scope $ WatchCollection ('item', function (value) {// if $ scope.selectedItem does not exist in the item array ( Value) $ scope.selectedItem = null;})}}); In the constructor for your controller, you can only set $ scope.    

to clear the selected ITem if the value is not present in the item array:

  $ scope.items = [{name: 'item1', id: 0}, {name: 'item2', id: 1}]; $ Scope. Selected item = ($ scope.items.indexOf ($ scope.selectedItem)! == -1)? $ Scope Selected Items: Nil;    

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -