gpt4 book ai didi

AngularJS Controller 继承

转载 作者:行者123 更新时间:2023-12-03 02:33:28 26 4
gpt4 key购买 nike

AngularJS 具有基于 DOM 的 Controller 继承,如 Angular 文档中所述。

<div ng-controller="BaseController">
<p>Base Controller Value: {{value}}</p>
<button ng-click="updateValue()">Update In Base</button>
<div ng-controller="DerivedController">
<p>Derived Controller Value: {{value}}</p>
<button ng-click="updateValue()">Update In Derived</button>
</div>
</div>

范围变量“value”仅存在于 BaseController 中。基于此,在更改 BaseController 或 DerivedController 中方法的值时,我希望这两个值都需要更新。但只有单个作用域变量会被更新。

这是一个演示相同示例的 fiddle :http://jsfiddle.net/6df6S/1/

如何在某个级别进行更改以传播到当前范围的直接子级和直接父级。

我们可以通过使用来实现它

$scope.$watch

有没有办法在不使用它或任何此类观察者的情况下做到这一点?

编辑1:

通过使用 $scope.$watch 这就是我的意思

$scope.$watch("value", function () {
$scope.$broadcast("childChangeListener"); //Downwards to all children scopes
$scope.$emit("parentChangeListener"); //Upwards to all parent scopes
});

我正在寻找在不使用这种机制的情况下在所有范围内更新值的方法。

最佳答案

当多个 Controller 需要访问相同数据时,service应该使用。您不应该依赖作用域继承,因为它限制了您编写 HTML 的方式。例如,将来,您决定 DerivedController 不应该是 BaseController 的子级。

您的服务通常应该提供公共(public) API,并隐藏实现。这使得重构内部更加容易。

HTML:

<div ng-controller="BaseController">
<p>Base Controller Value: {{model.getValue()}}</p>
<button ng-click="model.updateValue('Value updated from Base')">Update In Base</button>
<div ng-controller="DerivedController">
<p>Derived Controller Value: {{model.getValue()}}</p>
<button ng-click="model.updateValue('Value updated from Derived')">Update In Derived</button>
</div>
</div>

JavaScript:

app.factory('sharedModel', function () {
// private stuff
var model = {
value: "initial Value"
};
// public API
return {
getValue: function() {
return model.value;
},
updateValue: function(value) {
model.value = value;
}
};
});

function BaseController($scope, sharedModel) {
$scope.model = sharedModel;
}

function DerivedController($scope, sharedModel) {
$scope.model = sharedModel;
}

Fiddle .

此外,我不建议使用 $rootScope 在 Controller 之间共享。

关于AngularJS Controller 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15386137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com