지시문 격리 범위가 중첩된 뷰와 함께 제대로 작동하지 않습니까?(AngularJS/UI 라우터)
문제
저는 사용자 지정 지시어가 포함된 중첩 뷰가 있는 AngularJS 프로젝트에서 ui-router를 사용하고 있습니다.이 지시어는 입력 필드(예: 필터 필드)를 렌더링하며 해당 값은 컨트롤러 범위와 동기화되어야 합니다.
이는 뷰/상태가 중첩되지 않은 경우 이 지시문에 적합합니다.
var myApp = angular.module('myApp', ['ui.router', 'myComponents'])
.config(['$stateProvider', function ($stateProvider) {
$stateProvider.
state('home', {
url: '',
template: '<my-filter text-filter="theFilter"></my-filter><button ng-click="inspect()">inspect</button>{{ theFilter |json}}',
controller: 'myController'
});
}]);
var components = angular.module('myComponents', []);
components.directive('myFilter', [function () {
return {
restrict: 'E',
template: '<input type="text" name="filter" ng-model="textFilter">',
scope: {
textFilter: '='
}
};
}]);
components.controller('myController', ['$scope', function ($scope) {
$scope.theFilter = 'initial filter';
$scope.inspect = function () {
alert($scope.theFilter);
}
}]);
보다:
<div ng-app="myApp">
<div ui-View></div>
</div>
입력 필드의 텍스트를 변경하면 범위에 반영됩니다.
...하지만 뷰/상태를 중첩하면 범위의 값이 초기 값을 유지하지만 덮어쓸 때 입력 필드의 값에 따라 변경될 것으로 예상됩니다.
var myApp = angular.module('myApp', ['ui.router', 'myComponents'])
.config(['$stateProvider', function ($stateProvider) {
$stateProvider.
state('home', {
abstract: true,
url: '',
template: 'Nested View:<div ui-view></div>',
controller: 'myController'
}).
state('home.detail', {
url: '',
template: '<my-filter text-filter="theFilter"></my-filter><button ng-click="inspect()">inspect</button>{{ theFilter |json}}'
});;
}]);
var components = angular.module('myComponents', []);
components.directive('myFilter', [function () {
return {
restrict: 'E',
template: '<input type="text" name="filter" ng-model="textFilter">',
scope: {
textFilter: '='
}
};
}]);
components.controller('myController', ['$scope', function ($scope) {
$scope.theFilter = 'initial filter';
$scope.inspect = function () {
alert($scope.theFilter);
}
}]);
보다:
<div ng-app="myApp" >
<div ui-View></div>
</div>
여기서 스코프의 텍스트(컨트롤러 참조)는 동일하게 유지됩니다.
첫 번째 예에서와 같이 중첩된 뷰를 사용하여 동일한 결과를 얻을 수 있는 방법에 대해 알고 계시나요?
추신:지시어는 재사용 가능해야 합니다.
해결책
이는 일반적인 문제와 관련이 있습니다.이번 영상에서 언급했듯이 각도 JS - 모범 사례 (29:19) 여기에 설명되어 있습니다. Angular JS의 중첩 범위
"ng-model이 있을 때마다 어딘가에 점이 있을 것입니다.점이 없으면 잘못하고 있는 것입니다."
따라서 컨트롤러는 객체를 생성해야 합니다.
components.controller('myController', ['$scope', function($scope) {
// here theFilter is an object
// with property value
$scope.theFilter = { value : 'initial filter'};
$scope.inspect = function() {
alert($scope.theFilter.value);
}
}]);
템플릿은 속성이 있는 객체와 함께 작동해야 합니다. value
:
components.directive('myFilter', [function() {
return {
restrict: 'E',
template: '<input type="text" name="filter" ng-model="textFilter.value">',
scope: {
textFilter: '='
}
};
}]);
업데이트된 jsfiddle
제휴하지 않습니다 StackOverflow