【问题标题】:get ng-init value from scope从作用域获取 ng-init 值
【发布时间】:2015-12-19 05:17:03
【问题描述】:

我想从角度范围内获取 ng-init 值

控制器

$scope.data={}
$scope.initvalue="myvalue";

HTML

<input type="text" ng-model="data.value" ng-init="data.value= initvalue">

我想在输入框中设置 initvalue 并通过 ng-model 将它发送到控制器(我希望能够修改这个值,所以我需要这样做)

【问题讨论】:

    标签: javascript angularjs ng-init


    【解决方案1】:

    在html中

    <input type="text" ng-model="data.value" ng-init="setvalue()">
    

    在控制器中

     $scope.data ={}
        $scope.initvalue="myvalue";
        $scope.setvalue= function(){
            $scope.data.value = $scope.initvalue;
        }
    

    这可能对你有帮助!

    【讨论】:

    • 在你的例子中,这不应该是:
    【解决方案2】:

    您可以尝试使用 $watch。请试试这个演示 例如:

    <div ng-controller="yourController" >
        <input type="text" id="demoInput" ng-model="demoInput" ng-init="demoInput='value'" />
    </div>
    

    控制器中的代码

    var yourController = function ($scope) {
     console.log('demo');
     $scope.$watch("demoInput", function(){
        console.log($scope.demoInput);
     },1000);
    }
    

    【讨论】:

      【解决方案3】:

      这有意义吗?

      http://jsfiddle.net/c7bsrenu/2/

      var myApp = angular.module('myApp',[]);
      
      function MyCtrl($scope) {
        $scope.data={}
        $scope.initvalue="myvalue";
        $scope.$watch('data.value', function(newVal, oldVal) {
            console.log(newVal);
            console.log(oldVal);
        });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-09
        • 1970-01-01
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        相关资源
        最近更新 更多