mmattax
mmattax

Reputation: 27670

How can I access an expression in an AngularJS directive?

I'd like to make a directive that looks like this (passing in an expression):

<button ui:spin="form.submitting">Save</button>

But am unsure if it's possible (or how) to access the form.submitting expression. In the past I've done something like this:

<button ui:spinner-button ui:spin="form.submitting">Save</button>

Where I read the uiSpin attribute in the uiSpinnerButton directive, but I'd like to know how to do this "all in one"

Any ideas?

Upvotes: 0

Views: 57

Answers (3)

mmattax
mmattax

Reputation: 27670

I got it, my directive looks like:

.directive('uiSpin', function() {
    return {
        link : function(scope, element, attrs, ngModel) {

            scope.$watch(attrs.uiSpin, function() {

                // do stuff here...

            });
        }
    }

})

I based this off the source to ngShow: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngShowHide.js

Upvotes: 0

Mark Rajcok
Mark Rajcok

Reputation: 364697

For a non-isolated scope, use $parse:

myApp.directive('uiSpin', function($parse) {
   return function(scope, element, attrs) {
      var model = $parse(attrs.uiSpin)
      console.log(model(scope));
      // If you want to change the value in your directive:
      model.assign(scope, "???");
   }
});

If you don't need to modify the value, you can simply use $eval instead:

console.log(scope.$eval(attrs.uiSpin));

Upvotes: 1

DanS
DanS

Reputation: 18463

You should be able to reference it by defining the directive's scope as follows:

scope: {
    spin: '=uiSpin'
}

Inside the directive's linking function, it will be scope.spin.

Upvotes: 2

Related Questions