gpt4 book ai didi

javascript - 获取 Controller 的名称

转载 作者:行者123 更新时间:2023-12-03 04:16:39 26 4
gpt4 key购买 nike

var app = angular.module('app', [])
app.controller('MainController', function MainController() {})
app.controller('directiveCtrl', function directiveCtrl() {})


.directive('controllerName', function($timeout) {
return {
restrict: 'A',
template: '<div>My controller name is: {{cName}}</div>',
controller: 'directiveCtrl',
link: function($scope, elem, attrs) {
var name;
console.log("printing");
name = elem.controller().constructor.name;
$scope.cName = name;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<div ng-app="app" class="container">
<div id="target" ng-controller="MainController">
<div>Type1</div>
<div controller-name></div>
</div>
***************************************************
<div id="target" ng-controller="MainController">
<div ng-controller="directiveCtrl">Type2
<div controller-name></div>
</div>
</div>

<hr/>
</div>

您好,我正在尝试使用指令获取 Controller 的名称

  1. 类型 1:这里指令 controller-name 有一个名为 MainController 的父 Controller ,并且它自己的 Controller 在名为 directiveCtrl 的指令内定义......但是当我尝试访问 Controller 名称,我得到的名称是 MainController 而不是 directiveCtrl...为什么???
  2. 类型 2:在这里我得到了值directiveCtrl,因为它在外面......谁能详细解释一下吗提前致谢

最佳答案

来自 element.controller() 的文档:

controller(name) - retrieves the controller of the current element or its parent. By default retrieves controller associated with the ngController directive. If name is provided as camelCase directive name, then the controller for this directive will be retrieved (e.g. 'ngModel').

该函数获取使用ng-controller定义的父 Controller 。这是正常行为,正如您在类型 1 中所定义的:

  <div ... ng-controller="MainController">
...
</div>

类型 2 中:

  <div ...
<div ng-controller="directiveCtrl">
...
</div>
</div>

关于javascript - 获取 Controller 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com