我对 Angular 还很陌生,所以请原谅我的简洁/无知。
我想做的是在动态加载的 ASP.NET MVC 局部 View
中使用 angular
。所以我有一个带有按钮的页面,当单击该按钮时,我出去并获得部分 View 并将该 HTML
注入(inject)到该页面上的 DIV
中。
在这个局部 View 中,我想使用 Angular 。我想要一个带有 ng-controller="MainController as main"
、一些 {{main.Field1}}
和 {{main.Field2}} 的 div
,以及将创建 Controller 并设置这些字段值的脚本。
问题是分部 View 没有编译/解析/链接/任何angular
并且我的 Controller 方法永远不会被命中。
我在整个搜索过程中看到了对 $compile()
和 using 指令的引用,但它们似乎涉及更复杂的模板和诸如此类的东西,我还没有遇到一个精简的简单解决方案我想做的事。有人可以提供吗?
您可以按如下方式使用$compile
服务:
angular.module('application',[])
.controller("TestController", ['$scope', '$compile', function($scope, $compile){
var self = this;
self.OnShowCompiledHTML = function(){
var html = '<div data-ng-controller="OtherController as vm"><span>{{name}}</span><button data-ng-click="vm.OnShowFullName()">Show Full Name</button></div>';
var templateElement = angular.element(html);
var scope = $scope.$new(true);//pass in isolate as true as we dont need the parent scope
scope.name = 'John';
scope.surname='Doe';
var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
//attach the clone to DOM document at the right place
angular.element(document.querySelector('#container')).append(clonedElement);
});
};
}])
.controller("OtherController", ['$scope', function($scope){
var self = this;
self.OnShowFullName = function(){
alert('This is my fullName:' + $scope.name +' ' + $scope.surname);
};
}])
您可以在这里找到一个工作示例 https://jsfiddle.net/87h02o8r/
解释:
$compile
获取一个元素和一个 $scope
的实例。要动态创建新范围,您可以使用 $scope.$new(isolate, parent)
方法。
$scope.$new(isolate, parent)
有两个参数。
第一个参数表示您是否要创建一个从父范围继承的范围,如果不是,您正在创建独立的范围。
如果创建一个继承当前作用域的作用域,则需要传入当前作用域eg $scope.$new(false, $scope)
;
因为 HMTL 现在已兼容,您可以正常使用 OtherController
;
如果您需要获取 bootstrap Modals 或任何其他部分 HTML 功能的未编译部分 View ,这是一种注入(inject)已编译 HTML 的简便方法。
不像我那样对 HTML 进行硬编码,您将通过 $http
服务获取 HTML。