我的问题是我有一个 ng-app。这是否意味着我必须对我可能不会在给定 View 上使用的插件进行依赖注入(inject)?我引入 ngTagsInput
的示例是否意味着即使 View 不需要它我也必须这样做?这意味着我必须为每个 View 包含该 js,即使它不使用 ngTagsInput
。
我有一个非常大的 MVC .NET 应用程序,我正在尝试找出处理引入外部插件的最佳方法。
我在 Main _Layout 模板中有一些这样的代码:
<html ng-app="ourApp">
<head>
<!-- all of our includes are here -->
</head>
<body>
<directive></directive>
<anotherdirective></anotherdirective>
@RenderBody()
</body>
</html>
RenderBody 是 MVC 在我们的 View 中从我们的 mvc 路由中滑动的地方。该 View 可能看起来像这样:
<script src="~/Scripts/HomeAngular.js"></script>
<div ng-controller="HomeCtrl">
<directive3></directive3>
</div>
应用JS:
var app = angular.module('ourApp', ['ngTagsInput']);
有没有办法让我不必在每个 View 页面上注入(inject) ngTagsInput,即使我不需要它?
最佳答案
有几种不同的方法来处理 Angular 中的依赖注入(inject) (DI)。在第一个示例中,您只需在声明 Controller 之前定义 ngTagsInput
。例如,如果 ngTagsInput 是一项服务,您需要返回一个对象,其中包含允许您访问该服务内部数据的方法。
例如:
app.service('ngTagsInput', function($scope) {
var data = {};
return {
getData = function() {
return data;
},
setData = function(val) {
data = val;
}
};
});
app.controller('HomeCtrl', function($scope, ngTagsInput) {
// ...
$scope.tags = ngTagsInput; // whatever you want to do with it
});
However, there's a problem...
在上面的示例中,如果您通过压缩器运行该代码,您会将 $scope 转换为某个变量(a、b、x 等...),而 Angular 不知道如何处理它。
在这个方法中,我们使用了一个数组。数组中的最后一项是 Controller 的 lambda 函数,它为数组中的每个前一项接受 1 个参数:
app.controller('HomeCtrl', ['$scope', 'ngTagsInput', function(scp, ngTagIn) {
// ...
}]);
此代码可以通过压缩器运行得很好,因为依赖项是数组中的字符串,并且可以在函数参数内重命名为您想要的任何内容。
DI 也适用于具有相同语法的指令、工厂、过滤器和服务;不仅仅是 Controller 和模块。
app.directive('HomeCtrl', ['$scope', 'ngTagsInput', function(scp, ngTagIn) {
// ...
}]);
关于javascript - 原始 MVC 和 Angular 避免注入(inject)我不需要的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23916613/