0

point 1

i just do not understand why i could not access child controller property this way {{$scope.parentcities}}. but if i write like this way {{parentcities}} then it is working. so why we can not write $scope dot and then property name

<div ng-app ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl as vm">
       {{$parent.cities}}
       <br>
       {{$scope.parentcities}}
    </div>
</div>

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;
}

point 2

need some guide line what kind of syntax it is ChildCtrl as vm ?

when we need to mention controller in html ChildCtrl as vm like this way ?

does it carry any special meaning?

looking for some guidance. thanks

2 Answers 2

1

Well, the point of $scope is that you don't need to write it when you bind values to the view. So $scope.supervalue = 'Hallo' will be accessed in the view like this {{ supervalue }}. That's it.

$parentis a keyword from the Angular framework to reference the parent scope.

The controllerAs syntax is made to get rid of the $scope keyword alltogether. So inside the controller, you can write it like this:

var self = this;
self.supervariable = 'Hallo';

In your config for this route, you specifiy controllerAs: 'vm'. So you can access your values in the view via {{ vm.supervariable }}. Have a look here to learn all about it.

But, it seems like you should do some groundwork first and learn about the basic Angular mechanism before you dive into controllerAs, which has some tricky parts to it later on.

Sign up to request clarification or add additional context in comments.

2 Comments

see my fiddle jsfiddle.net/tridip/of8m9ep1/1 i use {{vm.parentcities}} but does not work. would you give your suggestion why it is not working.
I've updated it. Take care of your syntax. When you are using controllerAs, you need to use var self = this. jsfiddle.net/of8m9ep1/4 So, instead of just copying stuff from the internet, do some groundwork and learn it properly.
0

As long as you are going to use Ctrl as c syntax please assign values to this variable

function ParentCtrl($scope) {
  $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
  this.parentcities = $scope.$parent.cities;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="ParentCtrl">
  <div ng-controller="ChildCtrl as vm">
    {{$parent.cities}}
    <hr>
    {{vm.parentcities}}
  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.