问题
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