初始化时,ng-change和custom指令使范围变量未定义

时间:2014-06-06 07:38:43

标签: javascript angularjs

我正在使用ngModel探索角度自定义指令。我想了解执行流程和范围,因此我没有理解为什么它会给我意想不到的价值。

  • 当指令调用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

1 个答案:

答案 0 :(得分:1)

在代码中,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';
        }
    }
}]);
相关问题