我有一个看起来像这样的指令:
var myApp = angular.module('myApp',[])
.directive("test", function() {
return {
template: '<button ng-click="setValue()">Set value</button>',
require: 'ngModel',
link: function(scope, iElement, iAttrs, ngModel) {
scope.setValue = function(){
ngModel.$setViewValue(iAttrs.setTo);
}
}
};
});
问题是,如果我在页面中多次使用此指令,则仅在最后声明的指令上调用 setValue
。显而易见的解决方案是使用 scope: {}
隔离范围,但这样 ngModel 就无法在指令之外访问。
这是我的代码的 JSFiddle:http://jsfiddle.net/kMybm/3/
最佳答案
对于这种情况,ngModel 可能不是正确的解决方案。这主要是为了将值绑定(bind)到表单来执行诸如将它们标记为脏和验证之类的事情...
在这里,您可以只使用来自隔离范围的双向绑定(bind),如下所示:
app.directive('test', function() {
return {
restrict: 'E',
scope: {
target: '=target',
setTo: '@setTo'
},
template: '<button ng-click="setValue()">Set value</button>',
controller: function($scope) {
$scope.setValue = function() {
$scope.target = $scope.setTo;
};
//HACK: to get rid of strange behavior mentioned in comments
$scope.$watch('target',function(){});
}
};
});
关于javascript - 从指令设置 ngModel 时的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13045980/