我正在使用 v1.5 组件,它本质上(据我的理解延伸)是最佳实践指令的包装器。
有关组件 1.5 版本的更多信息可以在此处找到:http://toddmotto.com/exploring-the-angular-1-5-component-method/
我有以下内容:
<span>Correclty showing: {{ data.type }}</span>
<book class="details" type="data.type"></book>
它的组件定义:
angular
.module('app')
.component('book', {
bindings: {
type: '='
},
template: function($element, $attrs) {
// Have tried A):
// console.log($attrs.type); // <- undefined
// And B):
$attrs.$observe('type', function(value) {
console.log(value); // <- undefined
});
// But.. C):
return "This works though {{ book.type }}"; // <- renders
}
});
A)
和 B)
变体都返回 undefined
。 C)
正确渲染。
有没有办法在返回模板字符串之前访问模板函数中的属性?
最佳答案
在 1.5 中,templateUrl 现在根据文档接受可注入(inject):https://docs.angularjs.org/guide/component 。如果您使用ng-srict-di除非您指定可注入(inject)项,否则您将收到错误......我正在使用 ng-annotate避免麻烦并保持代码整洁。这是一个示例(使用 TypeScript):
import IRootElementService = angular.IRootElementService;
import IAttributes = angular.IAttributes;
angular.module('app').component('book', {
/*@ngInject*/
templateUrl($element:IRootElementService, $attrs:IAttributes) {
// access to the $element or $attrs injectables
}
});
或者在普通 JS 中没有 ng-annotate:
angular.module('app').component('book', {
templateUrl: ['$element', '$attrs', function($element, $attrs) {
// access to the $element or $attrs injectables
}],
});
关于angularjs - 如何访问 Angularjs v1.5 组件中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34263920/