【问题标题】:Angular JS $scope $watch issue - ionic frameworkAngular JS $scope $watch 问题 - 离子框架
【发布时间】:2015-10-28 23:00:14
【问题描述】:

我有一个带有状态设置的基本应用,例如:

.....config(function($stateProvider, $urlRouterProvider) {
   $stateProvider
   .state('tab.dash', {
      url: '/dash',
      views: {
        'tab-dash': {
          templateUrl: 'templates/tab-dash.html',
          controller: 'SearchCtrl as search'
         }
      }
    });
    .....
    $urlRouterProvider.otherwise('/tab/dash');

然后在制表符模板中我有以下内容:

<select class="item item-input" ng-model="formData.category"  ng-options="category as category.name for category in search.categories track by category.id">

SearchCtrl 有以下 $watch:

.controller('SearchCtrl', function($scope, service) {
    $scope.$watch('formData.category', function(cat){
      console.log("here");

是的,为了简洁起见,这些只是每个文件的摘录。代码结构基于其中一个离子样本。

控制台在初始页面视图中记录“此处”,但是一旦我对“formData.category”进行选择更改,就没有更多控制台日志了。当我有完全相同的代码时,在一个简单的 1 html 页面(非离子)角度应用程序中,我没有这个问题。 $watch 会检测到任何变化,但不是现在。

这真的让我很头疼。

有什么想法吗?

谢谢

【问题讨论】:

    标签: angularjs ionic-framework ionic


    【解决方案1】:

    你可以试试下面的吗?

    $scope.$watch('formData.category', function (newVal, oldVal) {   console.log("here"); }, true);
    

    请注意第三个参数(true)。

    Angular documentation

    来自文档,objectEquality(可选)使用比较对象相等性 angular.equals 而不是比较参考相等。

    如果上面的技巧不起作用,你也可以试试下面的。

     $scope.$watch(function ( $scope ) {
          return $scope.formData.category;
        }, function(newVal, oldVal){
            if(newVal != oldVal) {
                console.log('here');
    
            }
        });
    

    你能不能试试 ng-change

       <select class="item item-input" ng-model="formData.category"  ng-options="category as category.name for category in search.categories track by category.id" ng-change="valueChanged()">
    
         $scope.valueChanged = function(){
    // you can do what you are doing in $watch 
             console.log("here");
          }
    

    【讨论】:

    • 谢谢,#1 的想法没有任何区别。 #2 我收到一个错误,$scope.formData 未定义
    • 我已更新答案以将 $scope 参数添加到函数中。检查这个 $scope.$watch(function ( $scope ) 你能试试吗?希望它有帮助。
    • 你能试试 ng-change 一次吗?正如答案中更新的那样
    • 是的,ng-changed 有效。为什么手表不工作?我更喜欢使用 $watch 而不是更改。
    • 我找到了解决方案,并在此处添加了答案。谢谢。
    【解决方案2】:

    我用一些不错的老式头撞来解决答案,我在“SearchCtrl”控制器的顶部添加了以下行:

    $scope.formData = {};
    //...also $scope.formData = []; works too
    

    我不确定为什么在我的单个 html 页面、单个控制器常规 Angular js 应用程序中不需要此对象(或数组)声明,但在这里似乎是必需的。

    任何解释将不胜感激。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      相关资源
      最近更新 更多