我已经阅读了两篇博文:first表示它的工作原理和使用JSfiddle进行验证。 other says它只适用于基元。与Angular 1.5单向数据绑定,像双向工作
编辑@estus响应后:现在我做一个副本,因为排序不是一个不可变的函数。问题是不同的:在控制器中的更改不反映在单向视图,但它是与双向。
我工作过,also made a JSFiddle。我的单向数据绑定像对象一样双向工作 - 但是正确地使用了基元。当我使用ng-click来创建一个$ digest()时,它可以工作,但不直接在创建控制器时使用。哪里不对 ?
家长:
<body ng-controller="AppCtrl">
<users-component users="users"></users-component>
<button ng-click = "check()">Check current users in Parent Ctrl</button>
</body>
JS:
function UserCtrl($scope){
console.log('Component users at the controller start :', this.users);
this.sorting = function(){
this.users = angular.copy(this.users).sort();
console.log('Component users after sorting :', this.users);
};
//Change does not appear on View with one-way, but does with Two-ways
this.users = angular.copy(this.users).sort();
console.log('users in component after controller creation', this.users);
}
angular.module("demo", [])
.controller('AppCtrl', function($scope){
$scope.users = ['John', 'Jim', 'Albert', 'Luc', 'Sheldon'];
$scope.check = function(){
console.log('Application Ctrl : current users', $scope.users);
}
})
.component("usersComponent", {
template: '<ul><li ng-repeat = "user in $ctrl.users">{{user}}</li></ul>'
+'<button ng-click="$ctrl.sorting()">Sort users in Component Ctrl</button>',
controller : UserCtrl,
bindings:{
users : '<'
}
});
请注意,我现身为例还需要一个按钮,ng-click()
修改视图。
ouch,不可变... NOT。仍然有一个相同的问题有关的问题。 –
@NicolasZozol单向绑定对我来说看起来不错,至少在现代浏览器中是这样的:http://jsfiddle.net/21fx2s3x/。请澄清你期望从它那里得到什么样的行为。 – estus
用户应该在应用程序开始时进行排序。我们需要点击'排序用户'来显示。 –