0

On the Link below on plunker, I am trying to do a simple page connecting view 1 to view 2. On view 1 we can type a text which will be shown on View2.
My difficulty is trying to understand how I can connect the Controller1 mentioned in the $stateProviderState, to the Controller1.js, to the view. I find it difficult to understand how the factory works, how to do the injection.

Could anyone explain to me? Thank you.

Plnkr - Linking pages using ui-router

//app.module.js

var myApp = angular.module("myApp", ['ui.router']);

myApp.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when("", "/View1");

    $stateProvider
        .state("View1", {
            url: "/View1",
            templateUrl: "View1.html",
            view: {
              controller: 'Controller1'
            }
        })
        .state("View2", {
            url: "/View2",
            templateUrl: "View2.html",
            view: {
              controller: 'Controller2'
            }
         });
});

//Controller1.js

(function() {
  'use strict';
  angular
    .module("myApp")
    .factory('shareFactory', shareFactory)
    .controller('Controller1', Controller1);

  function Controller1(shareFactory, $scope, $http) {
    var vm = this;
    vm.textView1 = "SomethingToStartWith";

    function getView1() {
      shareFactory.getData()
        .then(function(response) {
          if (response.data) {
            vm.textView1 = response.data;
            console.log(vm.textView1);
          } else {
            console.log("Something was wrong");
            return;
          }

        }, function(response) {
          console.log("Entered this Error function");
        });
    }
  }
});

//Index.html

<!DOCTYPE html>
<html data-ng-app="myApp">

  <head>
    <script src="https://code.angularjs.org/1.5.5/angular.js" data-semver="1.5.5" data-require="[email protected]"></script>
    <script data-require="angular.js@<2" data-semver="1.5.7" src="https://code.angularjs.org/1.5.7/angular.js"></script>
    <script data-require="[email protected]" data-semver="1.0.0-alpha.5" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-alpha.5/angular-ui-router.js"></script>
    <script src="app.module.js"></script>
    <script src="Controller1.js"></script>
    <script src="share.factory.js"></script>
  </head>

  <body >

    <div class="header" ng-style="{background:'red'}">header</div>

      <div data-ui-view=""></div>

    <div class="footer" ng-style="{background:'blue'}">footer</div>
  </body>

</html>

//share.factory.js

(function() {
  angular
    .module("myApp")
    .factory('shareFactory', shareFactory);

  function shareFactory() {
    var data = '';

    return {
      getData: function() {
        return data;
      },
      setData: function(newData) {
        data = newData;
      }
    };
  }
})();
0

2 Answers 2

1

Maybe code explains itself?

Below code forked from your initial plunk can be found here http://plnkr.co/edit/WLe3TLTa6DKWUQ21lK3P

JavaScript

angular.module('myApp', ['ui.router'])
  .config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when('', 'view1');

    // set up states
    // no need to specify controllers in templates
    $stateProvider
      .state('view1', {
        url: '/view1',
        templateUrl: 'view1.html',
        controller: 'Controller1',
        controllerAs: 'vm'
      })
      .state('view2', {
        url: '/view2',
        templateUrl: 'view2.html',
        controller: 'Controller2',
        controllerAs: 'vm'
       });
  })

  // factory, shared data
  .factory('shareFactory', function($q) {
    var data = 'initial value';

    // mock $http using $q which returns
    // resolved/rejected promise, as would $http      
    return {
      getData: function() {
        return $q.when(data); // resolve
      },
      setData: function(val) {
        if (val.length > 0) {
          data = val;
          return $q.when(); // resolve
        } else {
          return $q.reject('value can\'t be empty'); // reject
        }
      }
    };
  })
  .controller('Controller1', function(shareFactory, $state) {
    var vm = this;

    // because async          
    shareFactory.getData()
      .then(function(data) {
        vm.data = data;
      });

    vm.set = function(data) {
      shareFactory.setData(data)
        .then(function() {
          vm.error = null;
          $state.go('view2');
        })
        .catch(function(e) {
          vm.error = e;
        });
    };
  })
  .controller('Controller2', function(shareFactory) {
    var vm = this;

    shareFactory.getData()
      .then(function(data) {
        vm.data = data;
      })
      .catch(function(e) {
        console.log(e);
      });
  });

index.html

<body >
  <div data-ui-view></div>
</body>

view1.html

<div>
  <h1>view1</h1>
  <label>Enter a value: </label>
  <input type="text" 
         ng-model="vm.data">
  <input type="button" 
         class="btn btn-default" 
         value="Go to view2"
         ng-click="vm.set(vm.data)">
  <pre ng-bind="vm.error"></pre>
</div>  

view2.html

<div>
  <h1>view2</h1>
  The value set in view1 is: <b ng-bind="vm.data"></b>
  <input type="button"
         class="btn btn-default"
         value="Go to view1"
         ui-sref="view1">
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Check the plunker. Injecting factory to controller, controller to main module and ui-routing

Check this

html

<div class="header" ng-style="{background:'red'}">header</div>

  <div ui-view></div>

<div class="footer" ng-style="{background:'blue'}">footer</div>

main Js

var myApp = angular.module("myApp", ['ui.router','ConrollerApp']);

myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/View1");

$stateProvider
    .state("View1", {
        url: "/View1",
        templateUrl: "View1.html"

    })
    .state("View2", {
        url: "/View2",
        templateUrl: "View2.html"

     });
 });  

Controller

var ctrl=angular.module("ConrollerApp",["Factory"])
ctrl.controller("AppController",function($scope,AppFactory){
 $scope.data=AppFactory.useData();
})

Factory

 var factoryapp=angular.module("Factory",[])
 factoryapp.factory("AppFactory",function(){

 return{
 useData:function(){
  var x=10;
 return x;
 }
}
})`

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.