Kev*_*son 30
我不确定这是一个很好的解决方案,但我能够$scope.controllerName使用这种技术注入:
app.config(['$provide', function ($provide) {
$provide.decorator('$controller', [
'$delegate',
function ($delegate) {
return function(constructor, locals) {
if (typeof constructor == "string") {
locals.$scope.controllerName = constructor;
}
return $delegate.apply(this, [].slice.call(arguments));
}
}]);
}]);
Run Code Online (Sandbox Code Playgroud)
然后
app.controller('SampleCtrl', ['$scope', '$log', function ($scope, $log) {
$log.log("[" + $scope.controllerName +"] got here");
}]);
Run Code Online (Sandbox Code Playgroud)
Tho*_*sen 11
因此,根据Kevin Hakanson的回答和Darkthread的评论,这段代码至少可以使用1.3.15:dev
app.config(['$provide', function ($provide) {
$provide.decorator('$controller', ['$delegate', function ($delegate) {
return function (constructor, locals, later, indent) {
if (typeof constructor === 'string' && !locals.$scope.controllerName) {
locals.$scope.controllerName = constructor;
}
return $delegate(constructor, locals, later, indent);
};
}])
}]);
Run Code Online (Sandbox Code Playgroud)
这对我也有用.当使用'ngRoute'选择控制器时,我需要一个函数来确定控制器名称是否与给定路径匹配,所以我这样做:
app.controller('navigation', function($scope, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样使用它:
<div ng-controller="navigation" class="container">
<ul class="nav nav-pills" role="tablist">
<li ng-class="{active:tab('home')}"><a href='#/'>home</a></li>
<li ng-class="{active:tab('dashboard')}"><a href='#/dashboard'>dashboard</a></li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我已经在我的配置中添加了路由,例如
angular.module('app', [ 'ngRoute' ]).config(
function($routeProvider) {
$routeProvider.otherwise('/');
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home'
}).when('/dashboard', {
templateUrl : 'dashboard.html',
controller : 'dashboard'
});
})
Run Code Online (Sandbox Code Playgroud)
小智 5
在控制器工厂功能中,只需尝试$ attrs服务
app.controller("MyController", ["$attrs", function($attrs){
var currentControllerName = $attrs["ngController"];
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40439 次 |
| 最近记录: |