nikk wong
nikk wong

Reputation: 8670

AngularJS — directive $parsing an evaluated expression onto the scope object

I am passing a string to my isolated directive with the @ scope configuration, hoping to be able to get that string as an object on the scope, which could then be assigned a value.

HTML

<div directive model="object.property.property"></div>

JS

directive('directive', function($parse) {
    scope: {
        model: '@' 
    },
    link: function (scope, elem, attrs) {
        var object = $parse(scope.model);
        object(scope);
        scope.object.property.property = 'newstring';
        // scope.object.property.property = 'newstring';
    }
});

I was hoping that this would allow me to get object.property.property onto the scope with a value of newstring.

It doesn't seem that I am using the $parse service correctly, but most of the examples I am finding are related to using $parse to convert JSON. How can I use parse to turn this string into an object on the directive's scope?

Thanks!

Upvotes: 0

Views: 664

Answers (1)

ngunha02
ngunha02

Reputation: 1729

Is this what you are looking for?

app.directive("mainDir", function($parse) {
  return {
     restrict: 'AE',
     scope: {
       model: '@'
     }
    template: '<div> hello: {{model}} </div>',
    link: function(scope, el, attrs) {
       el.on('click', function(evt) {
           evt.stopPropagation();
           evt.preventDefault();
           var object = $parse(attrs.model);
           scope.$apply(function() {
               object(scope);
           });
           object = 'new string';
           scope.model = object;
       })
  }
 }
})

Usage:

<div main-dir model="object.property.property"></div>

Upvotes: 1

Related Questions