분리 범위 및 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" ...>
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
'programing' 카테고리의 다른 글
| Dataframe 셀 내부의 목록을 별도의 행으로 폭발시키는 방법 (0) | 2023.10.27 | 
|---|---|
| CakePHP 데이터베이스 연결 "Myql"이 없거나 만들 수 없습니다. (0) | 2023.10.27 | 
| "림라프"가 무슨 뜻인지 아는 사람? (0) | 2023.10.27 | 
| 가장 유용한 사용자 제작 C마크로스(GCC에서도 C99)? (0) | 2023.10.27 | 
| 숫자에서 최하위 비트의 값을 얻으려면 어떻게 해야 합니까? (0) | 2023.10.27 |