gpt4 book ai didi

javascript - 我如何在 Controller 之前运行指令功能?

转载 作者:行者123 更新时间:2023-11-29 16:09:54 24 4
gpt4 key购买 nike

我需要在 Controller 之前调用指令函数(我需要作用域)。

var app = angular.module('docsRestrictDirective', []);

app.controller('Controller', ['$scope', function($scope ) {
$scope.changeDerictive();
}]);

app.directive('ngMyDer', function() {
return {
restrict: 'A',
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope.changeDerictive = function() {

console.log("changed");
};
}
}
}
}
});

http://plnkr.co/edit/NWb23rScg8zvPluGBWH5?p=preview

最佳答案

根据要求,这是带有 ui-router 的示例。首先,我们将为应用程序的基础定义一个 Controller 。

<body ng-app="myApp" ng-controller="AppBaseCtrl">
<main role="main">
<overlay-spinner></overlay-spinner>
<invite-success></invite-success>
<div ui-view></div>
</main>
</body>

现在在 ui 路由器中我们将定义我们的基本路由:

.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/desiredRoute');
$stateProvider
.state('desiredRoute', {
url: '/desiredRoute',
templateUrl: 'views/pathToTemplate.html',
controller: 'MyViewCtrl'
})
});

那么会发生什么呢?基础 Controller 运行,我们可以初始化所需的范围变量,然后我们运行指令,然后我们运行我们需要的 Controller 。

所以你有在所需 Controller 之前运行的指令。

如果我们想让 ui-router 更简洁,我们可以这样定义路由:

在路由配置中:

  .state('dashboard', {
url: '/dashboard',
templateUrl: 'views/templates/dashboard/dashboard-base.html',
controller: 'DashboardBaseCtrl',
abstract: true
})
.state('dashboard.main', {
url: '/main',
templateUrl: 'views/templates/dashboard/dashboard-main.html',
controller: 'DashboardMainCtrl'
})

然后在 dashboard-base 的 View 中:

<div myDirective></div>
<div ui-view></div>

当然在基础 Controller 中定义你想要的东西,正如你所看到的......基础 Controller 运行然后指令然后我们想要的 Controller 所以指令在 Controller 之前运行......

编辑

我已经按照你的要求创建了一个小插件......你会在这里看到没有超时指令在我们的主 Controller 使用基本 Controller 之前被调用我的例子是答案中的第一个例子

plunker with answer

关于javascript - 我如何在 Controller 之前运行指令功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429725/

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