davej / angular-classy

Cleaner class-based controllers with Angular 1
http://davej.github.io/angular-classy/
813 stars 27 forks source link

Is it possible to set a string as data that is not parsed? #48

Closed Lukenickerson closed 9 years ago

Lukenickerson commented 9 years ago

I'd like to be able to set a string in the data object but not have it parsed (e.g., a string of html). Currently this doesn't seem possible, but I'm not sure if I'm missing something.

Near line 310, in init:

if (angular.isString(value)) { var getter = this.$parse(value); data[key] = getter(klass);

Help text on the homepage:

You can use a string representing an angular expression, or you can directly assign any other object/primitive. [emphasis mine]

If not possible, will this capability be added at some point?

davej commented 9 years ago

It will still be parsed but you can put quotes inside the string to parse it as a string literal, so:

data: {
  foo: '"bar"'
}

If you absolutely don't want to have it parsed then you could also do:

data: function() {
  return {
    foo: 'bar'
  }
}

Sorry if the text is a little bit confusing on the homepage. By "any other", I meant any primitive/object other than a string.

Lukenickerson commented 9 years ago

I've found that as a work-around if I have string data that I want to be available class-wide and not parsed -- and it's okay if it's not in the $scope -- I can make a _data: { dontParseMe = 'somestring' } object rather than using data.

davej commented 9 years ago

Not sure what you mean, could you give a code example?

Lukenickerson commented 9 years ago

There might be values that you'd like shared between the methods and the init function, but you just don't want the strings parsed because it doesn't make sense. Sorry I don't have a good example, but maybe something like this...

app.classy.controller({
    name: 'example',
    inject: ['buttonService'],
    _data: {
        html: null;
    },
    method: {
        doSomething: function() {
            this._data.html = this.buttonService.getButtonHTML();
        }
    },
    init: {
        this._data.html = this.buttonService.getButtonHTML();
    }
});

If I use data, then the html string will be parsed, which could throw an inappropriate error. If I use _data then I can avoid having the strings parsed.

davej commented 9 years ago

Ah right, you could use angular.extend if you want them directly on the class angular.extend(this, this._data);.

You could also create a simple plugin for that too. I haven't tested this but it should work:

angular.module('classy-unparsedData', ['classy-core']).classy.plugin.controller({
  preInit: function(classConstructor, classObj) {
    if (classObj._data) {
      angular.extend(classObj, classObj._data);
    }
  }
});