3

for my angular i have the following:

this is the html

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

js file

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 file

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

for some reason when i checked the debug console, it comes undefined and initial value can't be set. any idea?

thank you

12
  • Try adding $scope.inputvar = "Hello World"; in your controller. Commented Jan 12, 2016 at 3:27
  • i tried and it works, but not with the data i want. Commented Jan 12, 2016 at 3:28
  • What exactly did you want the initial value to be, what did you set it to be and what did it show? Commented Jan 12, 2016 at 3:30
  • delcare $scope.datas before $http like this $scope.datas=[] Commented Jan 12, 2016 at 3:31
  • do you see any error in the console? Commented Jan 12, 2016 at 3:39

2 Answers 2

1

The typical way to declare the model in the controller... something like:

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;
    });
}])
Sign up to request clarification or add additional context in comments.

2 Comments

thanks @andand, i'm gonna be working with this inputvar inside the directive, is that the only way to set the initial value properly?
There are other ways... using a service to communicate between the controller and directive comes to mind; this allows you to abstract away some of the functionality from both the directive and the controller. However, the examples in the documentation at docs.angularjs.org/guide/directive uses this pattern frequently... initialize the model in the controller.
1

<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.