angularjs - 无法访问角度指令的隔离范围
问题描述
第一指令:
app.directive("myDirectiveOne", function($rootScope){
return {
templateUrl : "/custom-one-html.html",
restrict: "AE",
replace:true,
scope: {
somedata: "=",
flags: "=",
functionone: "&"
}
,controller: function($rootScope,$scope, $element) {
$scope.firstFunction = function(){
console.log("First function is getting called")
}
$scope.$on('firstBroadcast',function(event, data){
$rootScope.$broadcast('secondBroadcast', data)
});
}
第二条指令:
app.directive("myDirectiveTwo", function($rootScope){
return {
templateUrl : "/custom-two-html.html",
restrict: "AE",
replace:true,
scope: {
data: "=",
functiontwo: "&"
}
,controller: function($rootScope,$scope, $element) {
$scope.secondFunction = function(){
console.log("Second function is getting called")
$rootScope.$broadcast('firstBroadcast', {})
}
$scope.$on('secondBroadcast',function(event, data){
$scope.callSomeFunctionWithData(data);
});
$scope.secondFunction();
$scope.editFunction = function(x){
console.log("This is the edit function", x);
}
父控制器:
$scope.parentFuntion = function(){
console.log("No trouble in calling this function")
}
所以,问题是当我尝试从 html 模板调用函数时myDirectiveTwo
,处于活动状态的控制器是父控制器,而不是孤立的控制器。
可能与我正在使用的广播有关吗?
html代码:
<div ng-repeat="x in data">
<h5>{{x.name}}</h5>
<button ng-click="editFunction(x)">Edit</button>
</div>
奇怪的是我得到了数据值并且 ng-repeat 在加载时工作正常。但是,当我单击按钮时,它什么也没做。如果我在父控制器中添加相同的功能,它会被调用.. :( 如何使隔离范围控制器再次活动..?
解决方案
问题是 ng-repeat 创建了一个子范围,因此editFunction
最终位于父范围内。
来自文档
...每个模板实例都有自己的范围,其中给定的循环变量设置为当前集合项...
您可以通过获取按钮元素的范围并检查 $parent 来验证这是问题所在,因此angular.element(document.getElementsByTagName("button")).scope()
尽管考虑了代码异味,但您可以将 $parent 附加到您的函数调用以访问它,但请记住,这现在对您的 HTML 结构产生了依赖性。
<button ng-click="$parent.editFunction(x)">Edit</button>
推荐阅读
- postgresql - 在 psql 的一列中连接日期(时间戳)和小时(数字)列
- android - ExpandableListView - 更新或删除特定行而不调用 Activity 中的适配器
- sql - 已经插入的数据替换到另一个 UserId
- r - 无法通过 googleAnalyticsR 导出超过 1000 行
- java-8 - 这是使用java optional的正确方法吗
- c# - 使用 DistributedSqlServerCache 的 ASP.CORE 会话
- c++ - 模板默认参数丢失其引用类型
- sql-server - 如何将 MS SQL 转储恢复到 postgres?
- python - 我目前正在阅读“用 Python 自动化无聊的东西”,但我不知道为什么我的自动添加徽标和调整图像大小的项目不起作用
- spring - Spring Form 标记抛出 java.lang.IllegalStateException