angular根据scope属性创建元素
angular Create element based on scope attribute
我如何控制一个指令的模板基于$scope变量已经被评估(编译?)由angular?
例如,当$scope
app.directive('inputType', function(){
var template;
if ($scope.inputType === 'input') {
template = "<input ng-attr-my-attribute='" + $scope.myAttribute + "' />";
}
return {
restrict: 'E',
scope: {
inputType: '=',
myAttribute: '='
},
template: template
}
})
<inputType inputType="input" my-attribute="some value"></inputType>
在这个例子中,我希望元素类型(input, textarea, checkbox等)由一个动态的$scope
属性控制。
您将在模板中执行所有条件标记,并且您可以将该逻辑基于来自父控制器的双向绑定范围变量。此外,你没有在HTML中正确使用你的指令。你需要在你的标记中定义驼峰式和蛇形的指令。试试这个
演示index . html
<body ng-controller="MainCtrl">
<input-type-dir input-type="inputs.one"></input-type-dir>
<input-type-dir input-type="inputs.two"></input-type-dir>
<input-type-dir input-type="inputs.three"></input-type-dir>
</body>
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.inputs = {
one : 'text',
two : 'checkbox',
three : 'textarea'
};
});
app.directive('inputTypeDir', function(){
return {
restrict: 'E',
scope: {
inputType: '='
},
templateUrl: 'template.html'
}
});
template.html
<input ng-if="inputType !== 'textarea'" type="{{inputType}}">
<textarea ng-if="inputType === 'textarea'" cols="30" rows="10"></textarea>
或者,如果你不想创建一个孤立的作用域,如果你只需要传递字符串值,你可以直接访问link函数中的属性:
<input-type-dir foo="text"></input-type-dir>
<input-type-dir foo="checkbox"></input-type-dir>
<input-type-dir foo="textarea"></input-type-dir>
指令def
link: function(scope, el, attrs){
scope.foo = attrs.foo;
}
tempalte
<input ng-if="foo !== 'textarea'" type="{{foo}}">
相关文章:
- 在运行时创建元素时移到一边时出错
- 如何在动态创建元素的内联onclick事件中传递对象
- 在 jquery 中创建元素
- 当我动态创建元素时,选择的插件不起作用
- HTML javascript函数来创建元素
- 从外部 js 脚本创建元素并插入到 html 中
- 在 d3 中为数据列表创建元素
- 如何在循环中创建元素并将其添加到DOM中
- JQuery-创建元素并将其连接到其他html
- 创建元素更好还是只在html上准备好它们
- 挂钩文档.使用函数原型创建元素
- Javascript动态创建元素和onclick函数
- 从任何jquery选择器字符串创建元素的最有效方法
- 动态创建元素和添加onclick事件不起作用
- 在javascript中创建元素时,CSS转换规则固有地被覆盖
- 如何在特定的HTML标记下用JavaScript创建元素
- 如何根据我正在读取的节点的元素名称创建元素
- 使用Jquery在元素中创建元素
- 使用JavaScript创建元素并使用它
- 将托管 Bean 与 javascript 结合使用来创建元素