2016-01-12 57 views
3

我的角度我有以下:角:無法設置初始值輸入框

這是HTML

<div ng-app='mainApp' ng-controller='myControl'> 
    <mydirective datas="datas"></mydirective> 
</div> 

JS文件

var mainApp=angular.module('mainApp',[]) 
.controller('myControl',['$scope','$http',function($scope,$http){ 
    $http.get('./myjson.json').success(function(fdatas){ 
     $scope.datas=fdatas; 
    }); 
}]) 
.directive('mydirective',function(){ 
    return{ 
     restrict:'E', 
     scope:{ 
      datas:'=' 
     }, 
     template:"<input type='text' ng-model='inputvar'/>", 
     controller:function($scope,window){ 
     $scope.inputvar=$scope.datas[0].name; 
     } 
    } 
}); 

JSON文件

[{ name:'test'},{name:'test2'}] 

由於某種原因,當我檢查了調試控制檯,它未定義並且初始值無法設置。任何想法?

謝謝

+0

嘗試增加'$ scope.inputvar =「 Hello World「;'在你的控制器中。 – andand

+0

我試過,它的工作原理,但不是我想要的數據。 – luis

+0

你究竟想要什麼樣的初始值,你認爲它是什麼,它顯示了什麼? – andand

回答

0

申報控制器模型...喜歡的事的典型方法:

var mainApp=angular.module('mainApp',[]) 
    .controller('myControl',['$scope','$http',function($scope,$http){ 
     $scope.inputvar = "Hello World"; 
     $http.get('./myjson.json').success(function(fdatas){ 
      $scope.datas=fdatas; 
    }); 
}]) 
+0

謝謝@andand,我會在指令中使用這個inputvar,是否正確設置初始值的唯一方法是? – luis

+0

還有其他一些方法...使用服務在控制器和指令之間進行通信時想到;這使您可以從指令和控制器中抽象出一些功能。但是,https://docs.angularjs.org/guide/directive文檔中的示例經常使用此模式...在控制器中初始化模型。 – andand

+0

謝謝@andand我會看看 – luis

0

<html ng-app=''> 
 
    <head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script></head> 
 
    <body ng-init='var=10'> 
 
    <input type='text' ng-model='var'/> 
 
</body></html>