gpt4 book ai didi

javascript - 单击时如何从 Controller 获取数据到指令

转载 作者:数据小太阳 更新时间:2023-10-29 06:10:04 25 4
gpt4 key购买 nike

当我使用 ng-clicked 时,我试图从 Controller 将数据发送到指令链接函数,但是我未能将数据发送到指令,该指令在页面加载时调用第一次

这是我的html代码

 <h2 ng-click="clickMe(somedata)"> click </h2>

<my-directive my-key="myVal"> </my-directive>

这是我的 Controller

.controller('myController',function($scope){

$scope.clickMe=function(somedata){
$scope.myVal=somedata;
};

});

我的指令

.directive('myDirective',function(){
return{
restrict:'E',
scope:{
myKey:'='
},
templateUrl:'exampleTempl.html',
controller:'myController',
link:function(scope,elem,attr){
console.log(scope.myKey); // getting undefined
console.log(scope.myVal); //here i want the data from controller when i clicked on ng-click
}
}
});

最佳答案

您可以通过服务 传递数据,也可以为此使用$rootScope,但使用根作用域是不好的做法。所以,使用服务。应该有更多方法可以做到这一点,但服务非常好。

这里是通过服务传递数据的清晰示例:AngularJS Service Passing Data Between Controllers

另一个用于 $rootScope:How to pass an object using $rootScope?

更新:

您还可以通过$scope.$emit$scope.$broadcast 通过parent-child Controller 传递数据,但请记住,这仅适用于父子 Controller 。

但是你可以用 $rootScope 做同样的事情,比如 $rootScope.$emit$rootScope.$broadcast。如果您将使用它, Controller 之间的关系就不再重要了(“兄弟” Controller 也是如此)。

这篇文章应该对你有帮助:https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

关于javascript - 单击时如何从 Controller 获取数据到指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331234/

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