javascript - 使用 ng-init 将变量绑定(bind)到 Controller 中的值

标签 javascript html angularjs angular-ngmodel ng-init

我正在编辑器页面上工作。我从服务器收到一个 Json,其中包含:

{
    "Q_id": 1,
    "isMultipuleAns": 0,
    "Q_mediaType": "page"
}

我正在尝试将信息放入输入 div (type=text) 或 textarea div 中。

<textarea 
    type="text" 
    name="question_title" 
    ng-model="question.question_title" 
    ng-init="question.question_title=index"`>

在我的 Controller 中我有这样的东西:

app.controller("someController",function($scope,$location,$http){
    // some http requests that puts the mentioned jason in $scope.myJson
    $scope.index= $scope.myJson.Q_id;
}

无论我尝试什么,ng-init 只适用于静态字符串。我无法让真实身份出现在网站上。只得到一个空白的输入字段。

我是 html 和/或 Angular 新手...有帮助吗?

最佳答案

您不能使用ng-init正如您所做的那样,因为它在项目开始时当您的 View 出现时起作用。

那又怎样ng-init为我做事!?

ng-init used for calling functions from controller inside the view or set default values for variables (which didn't use as ng-model) for example:

 var controller = function($scope){
   $scope.makeNewId = function(){
      return 15899933666;
   }
 }

在此示例中,我们可以调用 $scope.makeNewId()直接在 Controller 中我们也可以在 view 时执行此操作编译为 ng-init="makeNewId()" ,如果您注意它在每个页面重新加载

我的代码出了什么问题!

在您要设置的代码中ng-modelng-init完全错误

如果你问为什么,那是因为你使用了这样的东西 question.question_title这意味着您有 object哪个名字是 question ;所以我可以轻松地在我的 Controller 中定义它:

 var controller = function($scope){
    $scope.question = {
      question_title: $scope.myJson.Q_id
    };
 }

关于javascript - 使用 ng-init 将变量绑定(bind)到 Controller 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44478854/

相关文章:

JavaScript 18 岁以下出生日期

javascript - 如何获取父元素的类?

html - 如何在 ng-repeat block 元素之间添加空格?

javascript - ng-click 不更新 ng-repeat 中的值

javascript - 具有基本身份验证的 jQuery AJAX 跨域

javascript - ReactJS 操作现有的 DOM 元素

javascript - 如何使用 AJAX 进行正确的 jQuery 用户身份验证

javascript - IE8 - 按钮背景图像不显示?

javascript - 如何获取所选内容中所有文本元素的边界框值?

angularjs - 如何使用 AngularFire 将图像上传到 firebase?