programing

분리 범위 및 ng-모델이 포함된 지침

css3 2023. 10. 27. 22:06

분리 범위 및 ng-모델이 포함된 지침

저는 고립된 범위와 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

분리된 스코프가 설정되지 않으면 정상적으로 작동합니다.

의견에서 설명한 바와 같이 일반적으로 자녀 범위를 사용하는 것은 권장되지 않습니다(scope: true아니면scope: { ... }ng-model 을 사용합니다.다만, 아룬은 스코프 속성을 추가로 생성해야 하므로,scope: true원시가 아닌 물체와 함께 사용할 수 있습니다.이는 원형 상속을 활용하기 때문에$parentneed:

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

fiddle

ngModel="model"은 격리된 스코프를 만들었기 때문에 새로운 격리된 스코프를 나타냅니다.AppController 범위를 참조하려면 $parent:

<test-ng-model ng-model="$parent.model" name="myel"></test-ng-model>

언급URL : https://stackoverflow.com/questions/18546913/directive-with-isolated-scope-and-ng-model