Don Rhummy Don Rhummy - 3 months ago 4
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>

The method is:

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

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


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

<!DOCTYPE html>


   <script src=""></script>

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


  <body ng-app="app" >
    <div ng-controller="myController">


Hope it helps!