2016-04-24 101 views
0

我已经阅读了两篇博文: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()修改视图。

回答

2

单向绑定在这里不是问题,它可以像为基元和对象宣告的那样工作。

问题是由Array.prototype.sort()引起的:

排序()方法代替排序数组的元素,并返回 阵列。

usersComponent范围this.usersAppCtrl范围$scope.users指代相同的对象。一旦它与this.users.sort()this.users = ...这里没有做任何事情)排序,它在两个范围内都被修改。若要更改此行为,请修改副本而不是原始对象:

function UserCtrl($scope){ 
    console.log('Component users at the start :', this.users); 
    this.users = angular.copy(this.users).sort(); 
} 
+0

ouch,不可变... NOT。仍然有一个相同的问题有关的问题。 –

+0

@NicolasZozol单向绑定对我来说看起来不错,至少在现代浏览器中是这样的:http://jsfiddle.net/21fx2s3x/。请澄清你期望从它那里得到什么样的行为。 – estus

+0

用户应该在应用程序开始时进行排序。我们需要点击'排序用户'来显示。 –