angularjsangularjs-templates

Does Angularjs support with in template?


If I have $scope.data={"user" {"firstname":test"}}, I am hoping to have template like

{% with data %} user name is {{ user.firstname }}

or

{% with data.user %} user name is {{ firstname }}

somthing like that, but I could not find it. I think it is not ideal to always use full path like {{ data.user.firstname }}

Any idea?


Solution

  • As far as I know AngularJS doesn't support with, that's python. I see no problems in accessing:

    {{ data.user.firstname }} 
    

    in your templates. If you don't like that "data." why don't you just assign:

    let data={ user: { firstname: "test"} };   
    $scope.user = data.user;
    

    and then you will be able to use in your templates:

    {{ user.firstname }}
    

    Another thing you can use is directive - set up your own custom directive and pass values you want through a binding that will give you property on $scope you want. So in HTML you could do something like this:

    <some-directive user="data.user" />
    

    and then in directive (given that you have module stored in variable app):

    app.directive('someDirective', function() {
      return {
        scope: {
          user: '='
        },
        template: 'Name: {{user.firstname}}'
      };
    });
    

    More about directives: https://docs.angularjs.org/guide/directive