delver delver - 5 months ago 18
AngularJS Question

AngularJS directive get inner element

I've got next directive:

(function() {
'use strict';

angular
.module('myApp')
.directive('inner', inner);

function inner () {

return {
restrict: 'A',
scope: false,
link: linkFunc
};

function linkFunc (scope, element, attrs) {

}
}
})();


And HTML:

<span inner>{{vm.number}}</span>


How can I access vm.number's value in linkFunc? I need to take value exactly from content of the span tag.

Answer

There are various ways you can do this but here are the 2 most common ways:

ngModel

You could use ng-model like so in your template:

<span inner ng-model="vm.number">{{vm.number}}</span>

In your directive you require the ngModel where you can pull its value:

.directive( 'inner', function(){
    return {
        require: 'ngModel',
        link: function($scope, elem, attrs, ngModel){
            var val = ngModel.$modelValue
        }
    }
})

declare isolate scope properties

<span inner="vm.number">{{vm.number}}</span>

.directive( 'inner', function(){
    return {
        scope: { inner:'=' } ,
        link: function($scope, elem, attrs){
            var val = $scope.inner
        }
    }
})

Some less common ways:

use $parse service to get the value

Using the template again:

<span inner="vm.number">{{vm.number}}</span>

Let's assume you're going to Firstly you'll need to inject the $parse service in your directive's definition. Then inside your link function do the following:

var val = $parse(attrs.inner)

inherited scope for read only

I don't recommend this, because depending on how you defined your directive's scope option, things might get out of sync:

  1. isolate (aka isolated) scopes will not inherit that value and vm.number will probably throw an undefined reference error because vm is undefined in most cases.

  2. inherited scope will inherit the initial value from the parent scope but could diverge during run-time.

  3. no scope will be the only case where it will stay in sync since the directive's $scope reference is the same scope present in the expression {{vm.number}}

Again I stress this is probably not the best option here. I'd only recommend this if you are suffering performance issues from a large number of repeated elements or large number of bindings. More on the directive's scope options - https://spin.atomicobject.com/2015/10/14/angular-directive-scope/