gpt4 book ai didi

javascript - ng-change 和自定义指令使范围变量在初始化时未定义

转载 作者:行者123 更新时间:2023-11-28 01:13:56 26 4
gpt4 key购买 nike

我正在使用 ngModel 探索 Angular 自定义指令。我想了解执行流程和范围,所以我没有得到以下内容,这就是为什么它给了我意想不到的值。

  • 为什么指令调用 ng-change 时 myVar 未定义?
  • 在调用 $setViewValue 之前是否需要通过 jQuery 风格的指令设置值?

HTML

<div ng-controller="myCtrl">
<input type="text" ng-model="myVar" ng-change="changeMe()" my-custom-dir/>

<button>{{myVar1}}</button>
</div>

JS

angular.module("myApp",[]).controller("myCtrl",["$scope",function($scope) {
console.log("myvar defined");
$scope.myVar = "jay";

$scope.changeMe = function() {
$scope.myVar1 = $scope.myVar;
console.log($scope.myVar)
}
}]).directive("myCustomDir",[function(){
return {
require:"ngModel",
link:function(scope,ele,attr,ctrl) {
console.log(ele);

ele.val("he")
//scope.$apply(function() {
ctrl.$setViewValue();
// });
}
}
}]);

JSFiddle Showing my problem

最佳答案

在代码中 myVar 未链接到指令。如果您想操作指令范围 - 您必须在指令中定义隔离范围。当 angularjs 自动为你处理时,使用 jquery 更新作用域变量并不好。

演示: http://jsfiddle.net/iamgururaj/37kXt/2/

指令:

directive("myCustomDir",[function(){
return {
scope:{
model:"=ngModel"
},
link:function(scope,ele,attr,ctrl) {
scope.model = 'he';
}
}
}]);

关于javascript - ng-change 和自定义指令使范围变量在初始化时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24076645/

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