加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 带隔离范围和ng模型的指令

发布时间:2020-12-17 08:27:52 所属栏目:安全 来源:网络整理
导读:我试图写一个使用隔离范围和ngModel指令的指令。 问题: 当在指令中更新模型时,调用方的值未更新。 HTML: test-ng-model ng-model="model" name="myel"/test-ng-model 指示: app.directive( 'testNgModel',[ '$timeout','$log',function ($timeout,$log)
我试图写一个使用隔离范围和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

如在注释中讨论的,通常不推荐使用ng-model的子范围(范围:true或范围:{…})。但是,由于Arun需要创建其他范围属性,scope:true可以与对象一起使用,而不是基元。这利用原型继承,所以$ parent不是neeed:
<test-ng-model ng-model="someObj.model" ...>

fiddle

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读