Sagie
Sagie

Reputation: 1074

Angular js - Binding to function

I have binding to function that looks something like that:

function func() {
    this.scopeVar = {
        bla: this.isolateScopeVar.bla,
        gla: this.isolateScopeVar.gla
    }
}

I have this html code:

<span>{{this.scopeVar.bla}}</span>
<span>{{this.scopeVar.gla}}</span>

My problem is that if the this.isolateScopeVar.blaor this.isolateScopeVar.gla has changed the span wouldn't updated without any trigger of func.

I can use this method which will work:

function func() {
    return {
        bla: this.isolateScopeVar.bla,
        gla: this.isolateScopeVar.gla
    }
}

<span>{{this.func().bla}}</span>
<span>{{this.func().gla}}</span>

But i think that this isn't the best way to do it.

There is any other way to do that correctly?

Upvotes: 1

Views: 53

Answers (2)

coudy.one
coudy.one

Reputation: 1420

It is possible. Here is example:

angular.module('app', [])
.component('appComponent', {
      template: [
        '<span>{{ $ctrl.getData().bla }}</span><br>',
        '<span>{{ $ctrl.getData().gla }}</span>',
      ].join(''),

      controller: function () {

        this.getData = function(){

          var isolateScopeVar = {}
          isolateScopeVar.bla = 'my item bla'
          isolateScopeVar.gla = 'my item gla'

          return {
              bla: isolateScopeVar.bla,
              gla: isolateScopeVar.gla
          }
        }
      }
});

Live demo is here

Upvotes: 1

FrontTheMachine
FrontTheMachine

Reputation: 526

let's start with, I hope you're using a recent version on angular, maybe with components, that have isolated scope.

inside the template you can access the controller with $ctrl.

<span>{{$ctrl.bla}}</span>

where bla is defined inside the controller declaration:

angular.module('whatever').controller('theNameController', {
    bindings: {
        bla: '<' // if you want this to be settable from who's using the component
    },
    controller: () => {
        bla = 42; // or declare it here if you want it be completely isolated
    },
    require: { },
    templateUrl: 'myTemplate.html'
}

Upvotes: 1

Related Questions