【发布时间】:2014-08-15 22:38:53
【问题描述】:
实际上,我只需要在某个地方放置一个可以访问 $scope 的可重用函数。
这是我正在尝试做的一个简化示例的尝试:Plnkr
我仍然掌握指令的窍门。
var app = angular.module('plunker', []);
app.directive('dir1', function() {
return {
restrict: 'AE',
link: function(scope, element, attrs) {
element.click(function() {
scope.message = "Hey Now";
scope.doSomething();
});
}
};
});
app.directive('dir2', function() {
return {
restrict: 'AE',
link: function(scope, elem, attr) {
scope.doSomething = function() {
alert($scope.message);
}
}
};
});
和:
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<dir1>click me</dir1>
</body>
</html>
【问题讨论】:
-
你永远不会在任何地方使用 dir2。你到底想达到什么目的?
-
我只想要一个可重用的函数来改变 DOM 并可以访问 $scope @JBNizet
-
可以被什么重用?如果只有一个指令 dir1 使用它,请将其放在 dir1 指令中。如果它实际上被几个人使用,请将其放在以范围为参数的服务中。
-
服务会很棒,但它也必须编译 html: $compile(canvas)($scope); $scope.$apply();我需要做的不仅仅是向它传递参数。 @JBNizet
标签: angularjs