gpt4 book ai didi

angularjs - 具有隔离范围和 ng-model 的指令

转载 作者:行者123 更新时间:2023-12-03 10:42:48 24 4
gpt4 key购买 nike

我正在尝试编写一个使用隔离范围和 ngModel 指令的指令。

问题:
当模型在指令中更新时,调用者的值没有得到更新。

HTML:

<test-ng-model ng-model="model" name="myel"></test-ng-model>

指示:
app.directive(
'testNgModel', [
'$timeout',
'$log',

function ($timeout, $log) {

function link($scope, $element, attrs, ctrl) {
var counter1 = 0, counter2 = 0;

ctrl.$render = function () {
$element.find('.result').text(JSON.stringify(ctrl.$viewValue))
}

$element.find('.one').click(function () {
if ($scope.$$phase) return;
$scope.$apply(function () {
var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
form.counter1 = ++counter1;
ctrl.$setViewValue(form);
});
});
$element.find('.two').click(function () {
if ($scope.$$phase) return;
$scope.$apply(function () {
var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
form.counter2 = ++counter2;
ctrl.$setViewValue(form);
});
});

$scope.$watch(attrs.ngModel, function (current, old) {
ctrl.$render()
}, true)
}

return {
require: 'ngModel',
restrict: 'E',
link: link,
//if isolated scope is not set it is working fine
scope: true,
template: '<div><input type="button" class="one" value="One"/><input type="button" class="two" value="Two"/><span class="result"></span></div>',
replace: true
};

}]);

演示: Fiddle

如果未设置隔离范围,则可以正常工作: fiddle

最佳答案

正如评论中所讨论的,通常不建议将子范围(scope: truescope: { ... })与 ng-model 一起使用。然而,由于 Arun 需要创建额外的范围属性,scope: true可以与对象一起使用,而不是原语。这利用了原型(prototype)继承,所以 $parent不需要:

<test-ng-model ng-model="someObj.model" ...>

fiddle

关于angularjs - 具有隔离范围和 ng-model 的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com