boneskull / angular-tags

Pure AngularJS tagging widget with typeahead support courtesy of ui-bootstrap
MIT License
133 stars 32 forks source link

Suggestion: When data model key doesn't exist, add it automatically (0.3.1) #38

Open WhatFreshHellIsThis opened 10 years ago

WhatFreshHellIsThis commented 10 years ago

I would like to see a feature added where the component will create a key on the data model if it doesn't already exist:

I am using this with a rest service backed by a document db. So when my record comes to the page there is a possibility that the key I've indicated as my data model for the tags simply doesn't exist.

For example, let's say I have a 'user' object in the scope and it never had any tags added to it, so the model would be 'user.tags' however that key doesn't exist yet which is natural and normal with a document database.

This results in an exception in 0.3.1 (non templates version):

 TypeError: Cannot set property 'length' of undefined
  at Object.fn (http://localhost:3000/vendor/angular-tags-0.3.1.js:455:41)
  at Scope.$digest (http://localhost:3000/vendor/angular.js:12251:29)
  at Scope.$apply (http://localhost:3000/vendor/angular.js:12516:24)
  at http://localhost:3000/vendor/angular.js:14023:36
  at completeOutstandingRequest (http://localhost:3000/vendor/angular.js:4300:10)
  at http://localhost:3000/vendor/angular.js:4601:7 

Specifically this block of code in the "watchTags" function:

...
      }
               else {
                 scope.model.length = 0;//<---- HERE IS THE ERROR
                 for (i = 0; i < value.length; i++) {
                   scope.model.push(value[i]);
                 }
               }
               watchModel();
...

Ideally I think, if a user specifies

<tags model="user.tags" 

If user exists on the scope then it should add the user.tags key automatically like other components do.

In the mean time I'm working around it by intercepting the record coming from the server and adding the empty key if it doesn't exist, however this is not ideal with a document database system.