简体   繁体   中英

Using curly brackets for specifying angular expressions in attributes

I am aware that in Angular its not recommended to use double curly brackets with expressions in attributes but why if they are still used those expressions evaluate in some cases and not in the others. Here's the plunker with the given example. The alert box here displays an empty string, but if you move $scope.mytest assignment outside of the service's 'then' function (as shown below) then it works fine. Is that a bug or expected behaviour?

app.controller('MainCtrl', function($scope, jsonService) {
  $scope.mytest = 'Bzzz';
  jsonService.getjson().then(function(d) {
    $scope.sourceData = d;
    $scope.loaded = true;
  });

});

EDITED:

The above condition can be observed when an attribute contains more than one expression, which should evaluate to scope variables. But if you leave only one expression in the attribute everything works fine :

<my-directive myattr="{{mytest}}">{{mytest}}{{mytest}}</my-directive>

even when the scope variable is set within the 'then''s function:

app.controller('MainCtrl', function($scope, jsonService) {
  jsonService.getjson().then(function(d) {
    $scope.mytest = 'Bzzz';
    $scope.sourceData = d;
    $scope.loaded = true;
  });

});

The problem is the double expression won't be reevaluated. So, in your first example, when the value is assigned directly to the $scope property (ie "at initialization"), your code will work.

However, once you move the assignment to the promise handler, the attribute expression won't be notified anymore of the changes.

If you want to make your example work, do so by combining the two expressions into one, like:

<my-directive myattr="{{mytest + mytest}}">{{mytest}}{{mytest}}</my-directive>

This is not about using {{}} in attributes. Html is view, js is model. You should access model from view, you should not access view from model.

Html is updated using $watchers, order of $watchers is not defined - your code should not depend on which watcher was run first, so you should not address result of one watcher in another watcher.

Had similar situation and simply done with:

<my-directive :myattr="mytest">{{mytest}}</my-directive>

if outside of HTML element (such as in attribute), use version with double curly braces.

Another example, with string + expression:

<a :href="'mailto:' + contactEmailAddress">{{contactEmailAddress}}</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM