Don Rhummy Don Rhummy - 4 months ago 11
AngularJS Question

How create new object in scope and have view's method calls use the new object?

I have a view like this:

<span ng-if="myobject == null" ng-init="createNewObj()"></span>
<div>checkIsNull(myobject)</div>


The method is:

$scope.createNewObject = function() { $scope.myobject = { name: "test"; } };


But when it runs, it always has
myobject
as null in the
checkIsNull
method. How do I create that object in the scope and have it used in the later parts?

Answer

well, i wouldnt use ng-if or ng-init for that. i would handle that in the controller. like this:

<!DOCTYPE html>

<html>

<head>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
 </head>

 <script>
 angular.module('app', [])
   .controller('myController', function($scope) {
     $scope.createNewObject = function() {
       $scope.myobject = { name: "test" };
     };
     function activate() {
       if(!$scope.myobject) {
          $scope.createNewObject();
       }
     }
     activate();

   });

 </script>
  <body ng-app="app" >
    <div ng-controller="myController">
      <span>{{myobject.name}}</span>
    </div>
  </body>

</html>

Hope it helps!