【问题标题】:How do i access a dynamically generated ng-model value of an input field using $scope.$watch in angularjs如何在 angularjs 中使用 $scope.$watch 访问输入字段的动态生成的 ng-model 值
【发布时间】:2015-12-21 12:34:06
【问题描述】:

我想访问一个动态生成的 angular-ngmodel
使用 $scope.$watch 的输入字段的值。 这是我的代码 sn-p 下面:

<body ng-app="myApp" ng-controller="myCtrl">
    <form>
        <input type="text" ng-model="<?php echo $product->id ?>" name="prid" />
        <input type="submit" value="Add to Cart" ng-click="yea()"/>
    </form>
</body>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.yea = function() {
            $scope.$watch('xxx', function(){
                var test = angular.copy($scope.xxx);
                alert(test);
            })
        };
    });
</script>

我实际上想做的事情:我想获得
的动态生成值 上面的文本字段,然后通过 angularJS 将其传递给 php 变量。 所以,我想到了上面的代码但是卡住了(不知道xxx是什么
会的)。请问,我做错了还是有什么解决办法 上面的代码?

谢谢

【问题讨论】:

  • ng-model of text field 没有关闭
  • 您的 JS 和 HTML 代码在同一个文件中?如果是,你可以做$scope.$watch('&lt;?php echo $product-&gt;id ?&gt;', function() {...

标签: angularjs angular-ngmodel


【解决方案1】:

您可以创建自己的指令:

<my-input my-input-id="{{'<?php echo $product->id ?>'}}"></my-input>

这样 php 应该用 id 替换它的代码,然后你就可以在你的指令中使用它:

app.directive('myInput', function() {
  return {
      restrict: 'E',
      scope: {
        myInputId: '@'
      },
      template: '<input ng-model="myInputId" />'
  };
});

请注意,我尚未测试此代码是否真的有效。如果您要创建 plunkr 或 jsfiddle,我将非常乐意看看。

但我个人永远不会以这样的方式打印出 php。每当我使用 PHP 和 Angular 时,我都会从 Angular 到 PHP API 进行 HTTP 调用。这样,您就可以清楚地区分 Angular 和 PHP 代码。

【讨论】:

    【解决方案2】:

    你可以使用ngInit来初始化你的模型,比如

    <input type="text" ng-init="initPrid(<?php echo $product->id ?>)" ng-model="prId" name="prid" />
    

    然后在你的控制器里面添加

    $scope.initPrid = function(id) {
      $scope.prId = id;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多