Equivalent of {{#with}} in angular

我们两清 提交于 2019-12-11 03:56:41

问题


What's the equivalent to {{#with}} in handlebars in angular? I'd like to create a sub scope with data from the result of a method call.

For example, I'd imagine it would be something like this (which obviously isn't correct):

<div ng-with="getData(myData)">{{name}}</div>

With myData as a value on the parent scope and name a property on the returned object.


回答1:


You can make your own

module.directive("ngWith", function() {
    return {
        scope: true,
        link: function(scope, elem, attr) {
            var result = scope.$parent.$eval(attr.ngWith);
            for (var prop in result) {
                if (result.hasOwnProperty(prop)) {
                    scope[prop] = result[prop];
                }
            }
        }
    };
});

in markup

<div ng-with="getData(myData)">{{name}}</div>

The expression inside the ng-with attribute is evaluated against the parent scope, each property in the return value will be binded to the new child scope created by the directive, under the same name.

I don't think there is much use for this directive though. If you just want to display the name property, just do {{getData(myData)['name']}} or save the result of the function to a scope variable



来源:https://stackoverflow.com/questions/24131910/equivalent-of-with-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!