我在一个AngularJS项目中使用ui路由器,其中我有一个嵌套视图,其中包含一个自定义指令。这个指令呈现一个输入字段(比如说过滤器字段),它的值应该与控制器的作用域同步。
当视图/状态not嵌套时,此操作对此指令很有效:
jsFiddle /不嵌套/按预期工作
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>当我更改输入字段的文本时,它会反映在范围上.
...but当我嵌套视图/状态时,作用域上的值保持它的初始值,但我希望它在覆盖时会根据输入字段的值进行更改。
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>在这里,作用域上的文本(参见控制器)保持不变。
知道如何使用嵌套视图获得与第一个示例相同的结果吗?
PS:指令需要保持可重用性。
jsFiddle /嵌套/不按预期工作
发布于 2014-04-13 13:29:59
这与一个共同的问题有关。如本视频角JS -最佳实践 (29:19)所述,并在此解释:角JS中的嵌套Scopes
“当你有ng模型的时候,一定有一个点在里面。如果你没有点,你就做错了。”
因此控制器应该创建一个对象:
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: '='
}
};
}]);向上的小提琴
https://stackoverflow.com/questions/23043216
复制相似问题