【发布时间】:2026-01-20 00:20:03
【问题描述】:
我在程序员的堆栈交换上问了这个问题,但没有得到任何答复,所以我想我会在这里碰碰运气......
我正在做一个项目,我想封装一个指令库并将其分发给其他开发人员使用。我想在这个封装的代码中保留对模型的更改,所以我真的不希望开发人员在 lib 之外更改范围变量。
在我的代码中,我有两种不同的方法可以从父控制器与我的库进行通信。
第一个理论是创建一个包含指令和服务的库。父控制器将调用该服务,该服务将处理对 lib 模型的所有更改,并且指令将根据这些更改做出反应。
第二个理论是将所有改变模型的函数放在指令本身中,并在父级上调用指令范围进行更改。
这是一个更详细地显示我所要求的内容的 plunker。这是一个简单的示例,但说明了两种不同的方法。
http://plnkr.co/edit/CR350Vx7NiHs5tkjNWZL?p=preview
我倾向于第二种方法,因为从开发场景中实现它看起来更简洁。
Angular 专家有什么建议吗?
Plunker Html:
<body ng-app="myApp">
This is Example 1 - Using a service to modify directive
<div ng-controller="Example1Ctrl">
<example1-directive ng-model='example1Model'></example1-directive>
<br>
<br>
<input type="button" value="Change Example 1" ng-click='changeExample1()' />
</div>
<br>
<br>
This is Example 2 - Modifying directive in the scope of the directive
<div ng-controller="Example2Ctrl">
<example2-directive ng-model='example2Model'></example2-directive>
<br>
<br>
<input type="button" value="Change Example 2" ng-click='changeExample2()' />
</div>
</body>
Plunker js
var app = angular.module("myApp", []);
//--------------------------------------------------
//-------- This is example 1
//--------------------------------------------------
app.controller("Example1Ctrl", function($scope, example1Svc) {
$scope.example1Model = {
value: "Example 1 - Original Value"
}
$scope.changeExample1 = function() {
example1Svc.change($scope.example1Model, "Example 1 - Changed Value");
}
});
/// This part would be encapsulated in a lib
app.directive("example1Directive", function() {
return {
restrict: "E",
scope: {
model: "=ngModel"
},
template: "{{model.value}}"
}
});
app.service("example1Svc", function() {
this.change = function(example1Model, newValue) {
example1Model.value = newValue;
}
})
// End lib
//--------------------------------------------------
//-------- This is example 2
//--------------------------------------------------
app.controller("Example2Ctrl", function($scope, example1Svc) {
$scope.example2Model = {
value: "Example 2 - Original Value"
}
$scope.changeExample2 = function() {
$scope.example2Model.change("Example 2 - Changed Value");
}
});
/// This part would be encapsulated in a lib
app.directive("example2Directive", function() {
return {
restrict: "E",
scope: {
model: "=ngModel"
},
template: "{{model.value}}",
controller: function ($scope) {
$scope.model.change = function(newValue) {
$scope.model.value = newValue;
}
}
}
});
// end lib
【问题讨论】:
-
我不明白 - 你是否试图从控制器的指令中调用函数?
-
在某种程度上。我正在尝试调用一个将修改指令外观的函数。我正在实现的现实世界指令是一个可分页的数据列表视图,我希望能够调用诸如 refresh()、firstPage()、lastPage() 等函数。问题是,我是否将它们放在一个服务并传入父作用域模型,还是我将函数放在父作用域模型上并调用它们而不需要传入模型(因为它已经在模型上)。
标签: angularjs angularjs-directive