我正在使用ngModel
探索角度自定义指令。我想了解执行流程和范围,因此我没有理解为什么它会给我意想不到的价值。
myVar
未定义?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();
// });
}
}
}]);
答案 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';
}
}
}]);