gpt4 book ai didi

javascript - 使用 controllerAs 语法通过指令 $watch 更改父 Controller 模型

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:13:20 25 4
gpt4 key购买 nike

我是 controllerAs angular 语法的新手,只是想了解它如何与指令一起使用。我已经为密码验证创建了一个指令。我想根据条件使一些标志为真,这些标志将在父模板中用于显示错误消息。我不明白我怎样才能做到这一点!

JSFiddle

查看

<div ng-app="myapp">
<fieldset ng-controller="PersonCtrl as person">
<input name="emailID" type="text" ng-model="person.first" >
<input name="pass" type="password" ng-model="person.pass" password-validator>
<p ng-show="person.showMsg">Password validation message here.</p>
</fieldset>
</div>

指令

myapp.directive('passwordValidator',function() {
return {
controller : PasswordCtrl,
controllerAs : 'dvm',
bindToController : true,
require : ['ngModel','passwordValidator'],
link : function(scope,ele,attrs,ctrls) {
var person = ctrls[1];
var ngModelCtrl = ctrls[0];

scope.$watch(function() {
return ngModelCtrl.$modelValue;
},function(newVal) {
if(newVal!='') {
person.showMsg = true;
} else {
person.showMsg = false;
}
console.log(person.showMsg);
});
}
}

function PasswordCtrl() {

}
});

Specially I want to understand why and how below watch is working fine!

// Why this below is also working, can anyone explain what's going behind!! 
scope.$watch('person.pass',function(newVal) {
console.log("Watch fires");
});

这只是为了学习目的,所以请解释 controllerAsbindToController 是如何工作的!

最佳答案

我知道这不是你问题的一部分,我会解决的,但使用指令“ng-controller”是一种反模式。如果有兴趣,我可以在单独的帖子中解释原因,但简而言之,这会使代码更难理解。

现在,进入问题的核心。

通过阅读 bindToController 的 Angular 文档可以看出,如果您还没有创建一个独立的范围,即 scope: truescope: {} 它什么都不做。

就我个人而言,我以前从未使用过它,而且似乎不是特别有用。

使用 ng-controller 本质上是使用该 Controller 对象向当前作用域添加一个属性。

所以:

<fieldset ng-controller="PersonCtrl as person">

实际上是在说,(以做作的方式):

$scope.person = new PersonCtrl();

你的指令 passwordValidator 在其中使用了 controllerAs 语法,基本上是这样的:

$scope.dvm= new PasswordCtrl();

在这种情况下,您实际上拥有一个范围对象,如下所示:

$scope = {
person = new PersonCtrl(),
dvm: new PasswordCtrl()
}

您的person Controller 和dvm Controller 是兄弟对象。在您的 passwordValidator 指令中,您需要在其 Controller 中使用 dvm 对象。使用那个 dvm 对象设置 person.showMsg 这与做的一样:

$scope.dvm.person.showMsg = <value>

dvm 对象无法访问 $scope 上的 person 对象,因为它们是 sibling 。所以你需要使用 $scope 本身来访问 person 对象。你需要做:

$scope.person.showMsg = <value>

虽然这假设范围内存在 person,但这是一个危险的假设。

关于javascript - 使用 controllerAs 语法通过指令 $watch 更改父 Controller 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39762036/

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