2017-10-13 43 views
1

比方说,我有一个组件如下:阅读组件控制器的值

.component('book', { 
    bindings: { 
     type: '=?' 
    },... 
}); 

所以在父控制器我已经宣布typevm.type = null;,并调用此组件为:<book type="vm.type" />

在这里,如果我在组件控制器的vm.type值设置为true我会得到价值true

所以,我要的是唯一的访问可以只设置组件控制器内,换句话说,父控制器内的vm.type值:vm.type是父控制器内部只读变量,但它可以被改变组件控制器。

一种方法结合自vm.type父控制器的值不会明显工作,如果我在组件控制器改变也不会改变。

我该如何解决呢?

+0

你想读的父节点的子控制器内部变量,对不对? –

+0

@CommercialSuicide不,我想读父控制器内部的组件控制器变量,这个变量只能改变组件的控制器内,并且不能在父控制器改变 –

回答

0

可以使用$emit$broadcast,父母和孩子控制器之间沟通,如果你想读父控制器子变量,可以执行以下操作:

child.controller

$scope.yourVariable = 'Data to send'; 
$scope.$emit('yourCustomEventName', $scope.yourVariable); // will emit event with data to parent controller 

parent.controller

// $scope.$on will catch your custom event 
$scope.$on('yourCustomEventName', function (event, data) { 
    console.log(data); // will print "Data to send", received from child controller 
}); 
0

如果您希望模型从父组件“只读”,那么您不必通过父组件对其进行更改。组件体系结构是树状的,所以父级高于子级。

综上所述,在你的情况,你只需要更新子组件模型,然后通过一些有约束力的事件传递父组件的更新值。

注意下面的代码,也here's a working fiddle demonstrating the following code

子组件:

.component('child', { 
    bindings: { 
    onValueChange: '&' 
    }, 
    controller: function() { 
    this.total = 0; 
    this.increaseTotal =() => { 
     this.total++; 
     this.onValueChange({ 
     value: this.total 
     }); // Here you updated the parent model 
    }; 
    }, 
    template: `<button ng-click="$ctrl.increaseTotal()">Increase total</button>` 
}) 

父组件:

.component('parent', { 
    controller: function() { 
    this.setValue = (val) => { 
     this.childValue = val; 
    }; 
    }, 
    template: `Total in Parent Component: {{$ctrl.childValue}} 
        <child on-value-change="$ctrl.setValue(value)"></child>` 
})