我已經閱讀了兩篇博文: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
用戶應該在應用程序開始時進行排序。我們需要點擊'排序用戶'來顯示。 –