无法从内部指令更改 ng-model
Cannot change ng-model from inside directive
我正在尝试创建一个从父 html 标签更改 ng-model
的指令,但它不起作用:
var app = angular.module('myApp',[]);
app.controller('ParentController',['$scope', function($scope) {
$scope.anyVar = "Anything";
$scope.list = ['It doesn\'t work','It also doesn\'t work'];
}]);
app.directive('customValue', [function() {
return {
restrict: 'A',
require: '^?ngModel',
link: function(scope, element, attr, ngModel) {
element.bind('click',function() {
var element = angular.element(this);
ngModel.$setViewValue(element.attr('custom-value'));
});
scope.$watch(function(){
return ngModel.$modelValue;
}, function(modelValue){
console.log("Wow, it was changed to : " + modelValue)
});
}
};
}]);
这是我的观点:
<div ng-app="myApp">
<div ng-controller="ParentController">
{{anyVar}}
<ul ng-model="anyVar">
<li>
<a custom-value="111">It' not working</a>
</li>
<li>
<a custom-value="222">It's not working as well</a>
</li>
<li>
----------------------
</li>
<li ng-repeat="item in list">
<a custom-value="333">{{item}}</a>
</li>
</ul>
</div>
</div>
如何使用和不使用 ng-repeat 从内部指令更新父 ng-model。
我创建了一个FIDDLE
基本上更新 ng-model
或来自事件的任何范围值将不会 运行 摘要循环,结果 angular 绑定不会在 UI 上更新,您需要通过 scope.$apply()
手动 运行 它。这将 运行 angular 摘要周期和绑定将在标记上更新。
代码
$scope.$apply(function(){
ngModel.$setViewValue(123);
});
我正在尝试创建一个从父 html 标签更改 ng-model
的指令,但它不起作用:
var app = angular.module('myApp',[]);
app.controller('ParentController',['$scope', function($scope) {
$scope.anyVar = "Anything";
$scope.list = ['It doesn\'t work','It also doesn\'t work'];
}]);
app.directive('customValue', [function() {
return {
restrict: 'A',
require: '^?ngModel',
link: function(scope, element, attr, ngModel) {
element.bind('click',function() {
var element = angular.element(this);
ngModel.$setViewValue(element.attr('custom-value'));
});
scope.$watch(function(){
return ngModel.$modelValue;
}, function(modelValue){
console.log("Wow, it was changed to : " + modelValue)
});
}
};
}]);
这是我的观点:
<div ng-app="myApp">
<div ng-controller="ParentController">
{{anyVar}}
<ul ng-model="anyVar">
<li>
<a custom-value="111">It' not working</a>
</li>
<li>
<a custom-value="222">It's not working as well</a>
</li>
<li>
----------------------
</li>
<li ng-repeat="item in list">
<a custom-value="333">{{item}}</a>
</li>
</ul>
</div>
</div>
如何使用和不使用 ng-repeat 从内部指令更新父 ng-model。
我创建了一个FIDDLE
基本上更新 ng-model
或来自事件的任何范围值将不会 运行 摘要循环,结果 angular 绑定不会在 UI 上更新,您需要通过 scope.$apply()
手动 运行 它。这将 运行 angular 摘要周期和绑定将在标记上更新。
代码
$scope.$apply(function(){
ngModel.$setViewValue(123);
});