1

Could you please explain why method 1 (binding to property) does not work, while method 2 (binding to function return value) does?

Including relevant code here. Please post a comment if you require any additional code.

function MyController(myService) {
    // Method 1: A property
    this.backgroundImagePath = login.backgroundImagePath;

    // Method 2: A function
    this.getBackgroundImagePath = function () {
        return login.backgroundImagePath;
    };
}

Then in my HTML code, I have:

<!-- Does not work -->
<img data-ng-src="{{ myController.backgroundImagePath }}" />

<!-- Works as expected -->
<img data-ng-src="{{ myController.getBackgroundImagePath() }}" />
Ricky
  • 2,850
  • 5
  • 28
  • 41
  • The error must be somewhere else, since both methods work in this [Plunker](http://plnkr.co/edit/ZYXIuzKZ1ghz3OrQJ6lE?p=preview). Can you add your own Plunker? – muenchdo Sep 29 '15 at 13:24
  • Because of time. The value of `login.backgroundImagePath` is not the same when it's read. – a better oliver Sep 29 '15 at 13:25
  • @zeroflagL: Thanks! So I understand that when login.backgroundImagePath is initially read, that it will not have the updated value. However, is there a way to have the value updated whenever login.backgroundImagePath changes? Or are functions the correct way to handle this – Ricky Sep 29 '15 at 13:33
  • Just found this [SO answer](http://stackoverflow.com/a/17493718/2375913), that should help! :) – muenchdo Sep 29 '15 at 13:37
  • You can add a watcher for `login.backgroundImagePath`. You can also [define a getter](http://stackoverflow.com/questions/32748257/angularjs-setting-properties-while-keeping-a-binding-is-there-a-better-way/32749039#32749039), which basically works like `getBackgroundImagePath ` in the background, but `login.backgroundImagePath` is still a property. – a better oliver Sep 29 '15 at 13:38
  • Thanks @zeroflagL: What is your recommendation on using the getter property in your example, versus just using a function to return the value? Is one the proper vs improper way? – Ricky Sep 29 '15 at 13:48
  • Thanks @muenchdo: However for my particular case, I don't need to hide the image, rather I just need the ng-src attribute to recognize when the property that it's referring to has changed and therefore update. Could your solution work for this instance? – Ricky Sep 29 '15 at 13:51

0 Answers0