Ng-change和custom指令在初始化时使作用域变量未定义

ng-change and custom directive makes scope variable undefined while initialization

本文关键字:作用域 变量 未定义 初始化 custom 指令 Ng-change      更新时间:2023-09-26

我正在用ngModel探索angular自定义指令。我想了解执行流程和作用域,所以我没有得到以下的东西,为什么它给了我意想不到的值。

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

<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显示问题

在代码中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';
        }
    }
}]);