S
S
Serg Sniffer2016-03-14 16:59:19
Angular
Serg Sniffer, 2016-03-14 16:59:19

How to properly pass $scope from child controller?

view:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
        <input type="text" ng-model="myText">
    </div>
    <button ng-click="click()">Click</button>
</div>

controller:
angular.module('app', [])
    .controller('ParentCtrl', [$scope, ParentCtrl])
    .controller('ChildCtrl', [$scope, ChildCtrl]);

function ParentCtrl($scope) {
  $scope.name = {title: ''};

  $scope.click = function() {
    console.log($scope.name);
  }
}

function ChildCtrl($scope) {
  $scope.$parent.name.title = $scope.myText;
}

If I explicitly redefine $scope.$parent.name.title = 'Test' in the child controller, everything works, but when I change the value in the input, no changes follow.
How to solve this problem correctly? Maybe you need to go in a different way? I ask for your opinion, gentlemen!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-03-14
@sniffer

How to solve this problem correctly?

Don't use $scope at all. Here in general. Do not inject it into controllers, and even more so into services. The only place where it should be is in the link of directives that work with the DOM (and for simple projects you don't even need to do this, because primitive directives like ngHide/ngIf cover most of the cases).
Don't use ngController at all. Today is angular 1.5, use components and bindings . Then this problem is already solved with the help of bindings, inheritance of scopes, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question