gpt4 book ai didi

javascript - 如何在 angularjs 中获取当前 Controller $scope 内部指令函数?

转载 作者:行者123 更新时间:2023-11-30 06:52:16 25 4
gpt4 key购买 nike

示例链接:Example

大家好

我在加载动态帮助(html 文件)时基于 url 在索引文件中创建了一个全局帮助按钮,它工作正常。我需要确定哪个 Controller 被激活,我需要将当前 $scope 作为参数传递给 $scope.HelpFunction 函数。$scope.HelpFunction 在帮助指令中可用。在指令中,我需要从当前 Controller 获取当前 $scope.message。基于 $scope 我需要实现很少的逻辑,任何人都可以帮助我......

  .directive("help", function($location, $window){
.directive("help", function($location, $window){
return {
restrict: "A",
template: "<button ng-click=\"HelpFunction( )\">Help</button>",
scope: true,
controller: function($scope){
$scope.HelpFunction = function( ){
//Here I need to access current $scope value
alert($scope.message)
//var url =$location.url();
//$window.open(url+ '.html', '', 'width=700,height=700');
}
},
link: function(scope){

}
}
})
.controller('HomeController', function ($scope, router, $location) {
$scope.message = "Home";
$scope.TestFunction = function(data) {
console.log("Home:" + $location.url())
};

})
.controller('MainController', function ($scope, router) {
$scope.message = "Main";
$scope.TestFunction = function(data) {
console.log("Main:" + data)
};

})
.controller('Page1Controller', function ($scope, router) {
$scope.message = "Page1";
$scope.TestFunction = function(data) {
console.log("Page2:" + data)
};

})

最佳答案

创建一个带有单例的工厂,并在每个 Controller 中保存当前作用域的引用。

factory('currentScope', function(){
var currentScope = {};

return currentScope;
})

controller('HomeController', function($scope, currentScope) {
currentScope = $scope;
})

controller('MainController', function($scope, currentScope) {
currentScope = $scope;
})

访问指令中的当前范围。

.directive("help", function($location, $window, currentScope){
return {
restrict: "A",
template: "<button ng-click=\"HelpFunction( )\">Help</button>",
scope: true,
controller: function($scope){
$scope.HelpFunction = function( ){
//Here I need to access current $scope value
console.log(currentScope);

alert($scope.message)
//var url =$location.url();
//$window.open(url+ '.html', '', 'width=700,height=700');
}
},
link: function(scope){

}
}
})

您必须为您的 View 分配一个 Controller 。

$stateProvider.state('Home', {
url: '/home',
templateUrl: 'Home.html',
controller: 'HomeController'
});

关于javascript - 如何在 angularjs 中获取当前 Controller $scope 内部指令函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35424167/

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