我有一个角控制器,它执行它通常的操作(根据请求,调用一个服务,获取数据并保存在它的范围内)。另外,我有一个指令,它的全部目的是使一个滑动的侧边栏菜单显示和隐藏(与一个轻微的动画)。菜单列表绑定到控制器操作的结果。
这样做的目的是通过单击屏幕上其他地方的按钮: 1.控制器操作将执行2.成功后,指令将被要求在菜单中滑动
我希望在没有控制器或指令对彼此有一点点了解的情况下发生这种情况。
是否有可能在HTML代码中编写绑定表达式,在更改菜单项列表时,它将调用指令的show()方法?
发布于 2015-05-22 14:18:49
通过引入名为onModelChange的第二个实用程序指令,我设法解决了这个问题。它使用ngModel侦听模型上的更改,当发生变化时,它调用第一个指令上的一个方法,该方法作为引用param传递。
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<a href="#" ng-click="doAction()">Call the controller</a>
<h2 ng-show="controllerCalled">controller called</h2>
<a custom-directive ng-click="show()">
<h2 ng-show="directiveCalled">directive called</h2>
<h2 ng-show="!directiveCalled">directive NOT called</h2>
</a>
<div ng-model="items" on-model-change="show()">
<div ng-repeat="item in items" >
<p>{{item}}</p>
</div>
</div>
</body>
</html>script.js
var myApp = angular.module('myApp', []);
myApp.controller('MainController', ['$scope',
function($scope) {
$scope.doAction = function() {
$scope.controllerCalled = true;
$scope.items = [1, 2, 3, 4, 5, 6];
}
}
]);
myApp.directive('customDirective', function() {
return {
restrict: 'A',
link: function($scope) {
$scope.show = function() {
$scope.directiveCalled = true;
}
}
}
});
myApp.directive('onModelChange', function() {
return {
restrict: 'A',
scope: {
model: '=ngModel',
onModelChange: '&'
},
link: function($scope, element, attrs) {
$scope.$watch('model', function(oldM, newM) {
if (oldM != newM) {
$scope.onModelChange();
}
})
}
}
});发布于 2015-05-22 09:21:30
是的,正确的方法是编写包含由指令和作用域共享并由控制器控制的方法和数据的服务(或工厂)。
这样的服务将在您的指令和控制器中注入。
https://stackoverflow.com/questions/30392797
复制相似问题