我有两个 Controller :'first-controller'、'second-controller' 和一个指令'executeOnEsc'。
我需要在这两个 Controller 之间“共享”此指令:该指令应调用 范围 1 中的 $scope.clear 函数并更改变量 范围 2 中的 someVar。
现在,正如您在代码片段中看到的那样,该指令会产生错误:scope.clear 不是函数。
这是有道理的,因为指令运行两次:首先在范围 1 中运行,然后在范围 2 中运行,后者没有“clear” 函数。
这种情况有什么解决办法吗?我可以制定两个不同的指令,但这不是最好的解决方案。
var app = angular.module('myApp', []);
app.controller('first-controller', function($scope) {
$scope.value = 'Scope 1 | Press ESC Key';
$scope.clear = function() {
$scope.value = 'Scope 1 value changed!';
}
});
app.controller('second-controller', function($scope) {
$scope.someVar = 'Scope 2 | Press ESC Key';
});
app.directive('executeOnEsc', function($document) {
return {
restrict: 'A',
link: function(scope) {
return $document.bind('keydown', function(event) {
if (event.which === 27) {
return scope.$apply(function() {
scope.someVar = 'Scope 2 value changed!';
scope.clear();
});
}
});
}
};
});
.someDiv {
background-color: #2ecc71;
padding: 10px;
margin: 5px;
}
.second {
background-color: #3498db;
padding: 10px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="myApp">
<div ng-controller="first-controller">
<div class="someDiv" execute-on-esc>
<p>{{ value }}
<p>
</div>
</div>
<div class="second" ng-controller="second-controller" execute-on-esc>
<p>{{ someVar }}
<p>
</div>
</section>
最佳答案
无需创建 2 个不同的指令,您只需要在第二个 Controller 中添加清除功能即可
var app = angular.module('myApp', []);
app.controller('first-controller', function($scope) {
$scope.value = 'Scope 1 | Press ESC Key';
$scope.clear = function() {
$scope.value = 'Scope 1 value changed!';
}
});
app.controller('second-controller', function($scope) {
$scope.someVar = 'Scope 2 | Press ESC Key';
$scope.clear = function()
{
$scope.someVar = ' Scope 2 value changed!';
}
});
app.directive('executeOnEsc', function($document) {
return {
restrict: 'A',
link: function(scope) {
return $document.bind('keydown', function(event) {
if (event.which === 27) {
return scope.$apply(function() {
scope.someVar = 'Scope 2 value changed!';
scope.clear();
});
}
});
}
};
});
.someDiv {
background-color: #2ecc71;
padding: 10px;
margin: 5px;
}
.second {
background-color: #3498db;
padding: 10px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="myApp">
<div ng-controller="first-controller">
<div class="someDiv" execute-on-esc>
<p>{{ value }}
<p>
</div>
</div>
<div class="second" ng-controller="second-controller" execute-on-esc>
<p>{{ someVar }}
<p>
</div>
</section>
关于javascript - 如何在多个 Controller 中使用一个指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846915/