Javascript 如何在angularjs中创建范围小部件
如何从页面中的html脚本创建小部件?假设我有:Javascript 如何在angularjs中创建范围小部件,javascript,jquery,html,angularjs,Javascript,Jquery,Html,Angularjs,如何从页面中的html脚本创建小部件?假设我有: <script type="text/html" id="widget-simple"> <div class="widget-simple"> This is my widget and he's called {{ test }} </div> </script> <script type="text/html" id="widget-complex">
<script type="text/html" id="widget-simple">
<div class="widget-simple">
This is my widget and he's called {{ test }}
</div>
</script>
<script type="text/html" id="widget-complex">
<div class="widget-complex">
This is my complex widget and he's called {{ test }}
</div>
</script>
我想创建一个具有以下范围的小部件:
function createWidget(name, class) {
var self = this;
this.name = name;
this.class = class;
}
var widgetList = [];
function createWidgetList() {
for(var i=0; j=3; i<j; i++) {
var class = i < 2 ? "simple" : "complex";
widgetList.push(new createWidget("widget "+i, class));
}
}
createWidgetList();
希望这一切都能在一个控制器中完成,但我正在尝试尽可能多地浏览JS,以确保我的要求是显而易见的。本质上,我将有一个小部件数组,每个小部件都有自己的属性。我可以修改这些属性,html将自动更新,但只针对该小部件,而不是所有小部件。所以在开始的时候,我应该在我的页面上有三个小部件,分别称为test1、test2和test3,因为它们都是div,没有其他内容,所以只有这个文本
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div ng-repeat="w in widgetList">
<!-- Somehow render the widget here -->
</div>
</div>
</div>
现在,您可能已经注意到我有两种不同类型的小部件,它们在两个脚本标记中定义。在创建时,我希望在获取模板化html时使用正确的脚本标记。一旦最初创建,小部件类就不需要更改html
有什么想法吗?想好了。。。样品
JS:
HTML
查看指令,但如何定义要动态使用的指令?或者是哪个对象。我想将其扩展为具有不同属性的完全不同的小部件。指令表示一个新的html元素,html属性将定义该新元素的接口。像任何html元素一样,您可以使它看起来像您想要的,并在您想要的地方重用它。阅读教程
var myApp = angular.module('myApp', []);
myApp.directive('one', function () {
return {
scope: {
},
restrict: 'AE',
replace: true,
template: '<div><p>{{text}}</p><button ng-click="changeText()">test</button></div>',
link: function (scope, elem, attrs) {
scope.changeText = function (txt) {
scope.index += 1;
scope.text = scope.index;
};
scope.restore = function () {
scope.text = "test",
scope.id = 1,
scope.index = 1
};
scope.restore();
}
}
});
myApp.directive('two', function () {
return {
restrict: 'E',
replace: true,
template: '<div>Directive two</div>'
}
});
myApp.directive('dynamic', function ($compile, $parse) {
return {
restrict: 'A',
replace: true,
link: function (scope, element, attr) {
attr.$observe('dynamic', function (val) {
element.html('');
var directives = $parse(val)(scope);
angular.forEach(directives, function (directive) {
element.append($compile(directive)(scope));
});
});
}
};
});
myApp.controller('MyCtrl', function ($scope) {
$scope.directives = ['<one/>', '<two/>'];
$scope.add = function (directive) {
$scope.directives.push(directive);
}
$scope.modifyText = function () {
var last = $scope.directives[$scope.directives.length - 1];
console.log(last);
last.changeText("tt");
}
});
<div ng-controller="MyCtrl">
<div dynamic="{{directives}}" ng-model="text"></div>
<button ng-click="add('<one/>')">Add One</button>
<button ng-click="add('<two/>')">Add One</button>
<button ng-click="modifyText()">change</button>
</div>