3

Can someone please help!

I am very much confused about this and $scope in angularJS.

Suppose here is my html:

<div ng-controller = "myController">
    <input type = "text" data-ng-model = "testing">
</div>

My controller

When I write:

$scope.testing = "Rest"; // this works fine

but:

this.testing  = "Rest" // this does not work

This works when I give alias to controller and use it

<div ng-controller = "myController as ctrl">
    <input type = "text" data-ng-model = "ctrl.testing">
</div>

Also here is my complete code where I am totally confused:

<div ng-controller = "myController as ctrl">
    <input type = "text" data-ng-model = "ctrl.testing">
</div>
<ng-form>
    {{testing}}
    <input type="button" ng-click="test()">
</ng-form>

Now in my controller

$scope.test = function(){
    this.testing = "Work" // This thing changes only the form variable not the actual why ??
}

And also ng-form does not create its own scope.. then

Also if in controller if I defined my test function

this.test = function() {

}// This is not called why?? 

Can someone please explain what's going on here. I am very much confused about this and scope.

Also $apply - does it also check my variables? Also this is not a duplicate i have many aspects which i am very much confused.

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Parshuram Kalvikatte
  • 1,616
  • 4
  • 20
  • 40
  • 3
    I was reading about the same [here](http://stackoverflow.com/q/11605917/1577396). That doesn't helped me. So, I am not voting to close this post. – Mr_Green Dec 14 '16 at 09:49
  • Might help - ['this' vs $scope in AngularJS controllers](http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers) – Ankit Dec 14 '16 at 09:52
  • `this.testing = "Work"` isn't changing a `ng-model` value on view because `$scope.test` function has different `this` than controller `this`. do place `this` inside controller like `var self = this;` & then do `self.testing = "work"`. *For 2nd question why `this.test` function isn't getting called?* you have to change your ng-click to `ng-click="ctrl.test()"` to make it working – Pankaj Parkar Dec 14 '16 at 09:53
  • Ya but my form does not create any scope so i need to write it ctrl.test? – Parshuram Kalvikatte Dec 14 '16 at 10:17

0 Answers0