$ scope在离子应用程序中返回undefined

时间:2017-01-30 10:40:17

标签: javascript angularjs cordova ionic-framework

我想知道$ scope的双重行为。在下面的脚本中,我将name的值视为警报。但是在我的离子应用程序中,相同的代码会警告undefined

我搜索了问题并发现this link作为解决方案,其中声明我们需要使用点(。)来获取ng-model中的值。两者有什么区别。



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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

尝试更改控制器功能,如下所示:

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

答案 1 :(得分:0)

实际上它确实适用于Ionic,

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

})

<强> DEMO

答案 2 :(得分:0)

解决方案:

&#34;如果您使用ng-model,则必须有一个点。&#34;
让你的模型指向一个object.property,你会很高兴。

<强>控制器

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

<强>模板

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

当孩子范围在起作用时会发生这种情况 - 如子路线或ng-repeats。 子范围创造了它自己的价值,名称冲突诞生as illustrated here

有关详情,请参阅此视频剪辑:https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s

这可以从以下链接中提及:

其他解决方案

  

使用this关键字代替$scopeMore details

此外,您可以从以下两个讨论中获得更多详细信息

Ng-model does not update controller value

Why is my ng-model variable undefined in controller?

更新解决方案1:

请先在控制器顶部声明空白对象:

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

我希望这些对您有所帮助。

答案 3 :(得分:0)

尝试使用json对象。

  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>