这是改变ng-include
控制器的动态方式吗?
我的应用程序允许用户创建页面一些内容和控制器。我可以更改ng-include
src,但我不知道如何动态关联新控制器。以下代码不起作用:
<div ng-app="MyApp">
<div ng-controller="ParentController">
<select ng-model="currentItem" ng-options="item as item.url for item in items track by item.url">
</select>
{{ currentItem }}
<div ng-include src="currentItem.url" ng-controller="currentItem.controller"></div>
</div>
</div>
我有以下JS:
var app = angular.module("MyApp",[]);
app.controller('ParentController', ['$scope',function($scope){
$scope.items = [{
url: 'page1.html',
controller: 'Page1Controller'
},
{
url: 'page2.html',
controller: 'Page2Controller'
}];
$scope.currentItem = {};
}]);
app.controller('Page1Controller', ['$scope',function(){
alert('Page1');
}]);
app.controller('Page2Controller', ['$scope',function(){
alert('Page2');
}]);
答案 0 :(得分:2)
我已经完成了使用指令:
$(function () {
//When any of the buttons is clicked, we store in the form data the clicked button value
$('#ajaxform').on('click', 'input[type=submit][name=feeling]', function(e) {
$(this.form).data('clicked', this.value);
});
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr("method"),
data: { clickedButton : form.data('clicked') } //Retrieve the button clicked value from the form data
});
});
});
JS指令:
<div ng-include src="currentItem.url" dyn-controller="currentItem.controller"></div>
这里的技巧是观察属性更改,添加app.directive('dynController', ['$compile', '$parse',function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem, attrs) {
// Parse the scope variable
var name = $parse(elem.attr('dyn-controller'))(scope);
elem.removeAttr('dyn-controller');
elem.attr('ng-controller', name);
// Compile the element with the ng-controller attribute
$compile(elem)(scope);
};
}]);
然后编译元素。
感谢
How to watch property in attrs of directive
和
答案 1 :(得分:0)