$ scope returns undefined in ionic application

I am wondering about the double behavior of $ scope. In the below script, I get the value name as a warning. But in my ionic application, the same code warns undefined .

I searched for the problem and found this link as a solution, which says that we need to use a dot (.) To get the value in ng-model , What is the difference between the two.

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.a =function a(){alert($scope.name);} }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> Name: <input ng-model="name" ng-blur="a()"> </div> 
+5
source share
4 answers

Try changing the function of the controller as shown below:

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.a =function(){ alert($scope.name); } }); 
0
source

He actually works with Ionic,

 angular.module('starter.controllers', []) .controller('myCtrl', function($scope) { $scope.a = function a() { alert($scope.name); } }) 

Demo

0
source

Decision:

"If you are using an ng model, you must have a point."
Make your model point in object.property and you will go well.

controller

 $scope.formData = {}; $scope.check = function () { console.log($scope.formData.searchText.$modelValue); //works } 

Template

 <input ng-model="formData.searchText"/> <button ng-click="check()">Check!</button> 

This happens when child areas are in the game - for example, children's routes or ng-repeats. The child array creates its own value, and a name conflict occurs as shown here :

See this video for more information: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s .

And this applies to the links below:

Other solutions

Use the this instead of $scope , Details



And also you can get more details from this below two discussions

Ng model does not update controller value

Why is my ng-model variable undefined in the controller?


Solution for update 1:

Please declare an empty object first at the top of your controller:

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.name = ""; $scope.a = function(){alert($scope.name);} }); 

I hope this helps you.

0
source

Try using a json object.

  var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.user = {'name':''}; $scope.a =function a(){alert($scope.user.name);} }); <div ng-app="myApp" ng-controller="myCtrl"> Name: <input ng-model="user.name" ng-blur="a()"> </div> 
0
source

Source: https://habr.com/ru/post/1263569/


All Articles