kma*_*man 9 jquery using-directives widget angularjs
我的目标是了解如何正确使用angularJS.我希望能够使用angularJS将选择的变量绑定到动态更改DOM结构.我不认为我完全理解角度提供的文档,我没有在这里或其他地方找到任何示例.任何帮助表示赞赏.
这个想法是我有这个用例,我首先从选择的类型开始,然后从选择的类型开始,创建适当的输入类型元素,然后用ng-model记录(例如从textareas到复选框) ,一直由angularjs控制器控制验证/限制.我已经习惯了在页面上使用可克隆元素并使用jQuery销毁和创建新元素的想法,但我一直在阅读控制器不应该有这个逻辑,而应该使用指令/小部件创建.我没有看到任何指令或小部件以这种方式被操纵的例子,但是我甚至不确定如何继续.我是否可以使用指令以这种方式操作DOM,而不仅仅是基于观察元素的多次操作?
我想做什么的例子.
$scope.types = ['Type1','Type2']
// something along the lines of...
$scope.layouts = {'Type1':['textarea','textarea'], 'Type2':['numeric','datepicker']}
Run Code Online (Sandbox Code Playgroud)
选择类型1:
选择类型2:
谢谢,
-JR.
Liv*_* T. 13
我就是这样做的.请注意,这只是一个起点.在相应的输入中仍然存在绑定到特定值的问题.我希望它有所帮助.
标记:
<html ng-app="App" ng-controller="MainCtrl">
<body>
<component index="0"></component>
<component index="1"></component>
Current type: {{type}}
<button ng-click="toggleType()">Toggle</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
指示:
var ngApp = angular.module('App', []).directive('component', function() {
var link = function(scope, element, attrs) {
var render = function() {
var t = scope.layouts[scope.type][attrs.index];
if (t === 'textarea') {
element.html('<' + t + ' /><br>');
}
else {
element.html('<input type="' + t + '"><br>');
}
};
//key point here to watch for changes of the type property
scope.$watch('type', function(newValue, oldValue) {
render();
});
render();
};
return {
restrict : 'E',
link : link
}
});
Run Code Online (Sandbox Code Playgroud)
控制器:
var MainCtrl = function MainCtrl($scope) {
$scope.type = 'Type1';
$scope.types = [ 'Type1', 'Type2' ];
$scope.layouts = {
'Type1' : [ 'textarea', 'textarea' ],
'Type2' : [ 'number', 'text' ]
};
$scope.toggleType = function() {
if ($scope.type === 'Type1') {
$scope.type = 'Type2';
}
else {
$scope.type = 'Type1';
}
};
};
Run Code Online (Sandbox Code Playgroud)