Friday, May 31, 2013

javascript - AngularJS multiple uses of Controller and rootScope - Stack Overflow

javascript - AngularJS multiple uses of Controller and rootScope - Stack Overflow


I would suggest to use a service that holds the menu and its methods. The service will then broadcast changes to the controller(s).
See a working plunker here: http://plnkr.co/edit/Bzjruq
This is the sample JavaScript code:
angular
 .module( 'sampleApp', [] )
 .service( 'MenuService', [ '$rootScope', function( $rootScope ) {
   return {
      menu: [ 'item 1' ],
      add: function( item ) {
        this.menu.push( item );
        $rootScope.$broadcast( 'MenuService.update', this.menu );
      } 
   };
 }])
 .controller( 'ControllerA', [ 'MenuService', '$scope', function( MenuService, $scope ) {
   $scope.menu = MenuService.menu;

   $scope.addItem = function() {
    MenuService.add( $scope.newItem );  
   };

   $scope.$on( 'MenuService.update', function( event, menu ) {
     $scope.menu = menu;
   });
 }]);
And the sample Html page:



   lang="en">
     charset="utf-8">
    </span><span class="pln" style="margin: 0px; padding: 0px; border: 0px; vertical-align: baseline; background-color: transparent;">Custom Plunker</span><span class="tag" style="margin: 0px; padding: 0px; border: 0px; vertical-align: baseline; background-color: transparent; color: rgb(128, 0, 0);">
    
    
  

   ng-app="sampleApp">

    
ng-controller="ControllerA">
  • ng-repeat="item in menu">{{item}}
  • type="text" ng-model="newItem" /> type="submit" ng-click="addItem()" />
    ng-controller="ControllerA">

    • ng-repeat="item in menu">{{item}}



    • share|improve this answer

      Thursday, May 30, 2013

      Netlobo.com | Get URL Parameters Using Javascript

      Netlobo.com | Get URL Parameters Using Javascript

      Get URL Parameters Using Javascript

      An easy way to parse the query string in your URL to grab certain values.

      Published Aug 17, 2006 by lobo235 
      Last updated on May 19, 2009
      Most of the server-side programming languages that I know of like PHP, ASP, or JSP give you easy access to parameters in the query string of a URL. Javascript does not give you easy access. With javascript you must write your own function to parse the window.location.href value to get the query string parameters you want. Here is a small function I wrote that will parse the window.location.href value and return the value for the parameter you specify. It does this using javascript's built in regular expressions. Here is the function:
      function gup( name )
      {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
        else
          return results[1];
      }
      The way that the function is used is fairly simple. Let's say you have the following URL:
      http://www.foo.com/index.html?bob=123&frank=321&tom=213#top
      You want to get the value from the frank parameter so you call the javascript function as follows:
      var frank_param = gup( 'frank' );
      Now if you look at the frank_param variable it contains the number 321. The query string was parsed by the regular expression and the value of the frank parameter was retrieved. The function is smart in a couple of ways. For example, if you have an anchor in your URL like our example URL above does (#top) the gup() function knows to stop before the # character. Also, if a requested parameter doesn't exist in the query string then an empty string is returned instead of a null.
      This function has worked very well for my query string parsing needs and should work well for you.

      Monday, May 13, 2013

      authentication - Cross-domain login using JSONP and cookies - Stack Overflow


      We all know that cookies are not accessible cross-domain as this presents a security risk. However, using some trickery, there are ways around this. Basically we are setting a cookie for the user on a central domain, checking for that cookie's existence using a script, then using a JSON-P callback to copy that cookie onto the other domains. In more detail:

      Logging In

      Step 1
      The 
       displayed on mydomain.com (or myotherdomain.com, etc) should POST tocentral.com/login
      Step 2
      On central.com/login, the username and password are verified and a cookie is set on thecentral.com domain containing a unique value for that user. The user is then redirected back tomydomain.com
      SELECT unique_value FROM users WHERE username = $username
      set cookie on central.com containing unique_value
      
      Step 3
      Back on mydomain.com we embed a script call to central.com/check.
      
      
      Step 4
      On central.com/check we check if the unique cookie is set for the user. Then we embed a JavaScript callback (JSON-P) that informs mydomain.com that the user is logged in. No sensitive user data is included, otherwise hacker.com could embed this script and get the user's information. Instead, we create a disposable hash based on the timestamp, so that mydomain.com can verify the authentication.
      if cookie on central.com is valid
          user_data = array(
             'success' => true,
             'uid'     => $uid,
             'time'    => time_stamp,
             'hash'    => disposable_salted_hash( $uid, time_stamp )
          )
          echo 'setDomainCookie(' . json_encode(user_data) . ')'
      
      Step 5
      The callback function is then executed, setting the cookie on mydomain.com. Finally, we can either refresh the page or just alert the user using JavaScript that they are logged in (preferably both).
      function setDomainCookie( user_data ) {
          if( user_data.success ) {
              $.post('/setcookie', user_data, function() {
                  location.reload(true);
              }
          }
      }
      
      mydomain.com/setcookie is similar to Step 2. Of course this assumes both sites have access to the same database (and code)
      if hash = disposable_salted_hash( $uid, time_stamp )
          SELECT unique_value FROM users WHERE uid = $uid
          set cookie on mydomain.com containing unique_value
      
      Step 6
      The next time the user refreshes the page, we can bypass the JSON-P callback
      if cookie on mydomain.com is valid
          loggedin = true
      else
          delete cookie on mydomain.com
          proceed to Step 3
      

      Logging Out

      Step 7
      The link on mydomain.com should go to central.com/logout
      Step 8
      On central.com/logout, not only is the cookie deleted, but the unique value for that user is reset. The user is redirected back to mydomain.com
      delete cookie on central.com
      UPDATE users SET unique_value = new_random_value() WHERE username = $username
      
      Step 9
      Now that the unique value is reset, Step 6 from above fails, the cookie is also deleted frommydomain.com, and the user is effectively logged out.

      Notes

      1. It is critical that central.com/check from Step 4 has the correct headers set so that it is not cached.
      2. Steps 3-5 when the user is logging in may cause a slight delay. It's wise to both refresh and show some kind of JavaScript alert that they are logged in. It's also important for the script from Step 3 to be as close to the top of the page as possible.
      3. In Step 5, you can optionally store a unique cookie value on each domain.
      4. The separate central.com domain is not really necessary; you can just use one of the other domains as the central domain if you wish. The logic for that domain would obviously be different.
      5. For this to work on Internet Explorer you will need a P3P policy attached to your cookies.
      6. Hope this is helpful to people. I'd be very interested to receive feedback, especially if there are any security flaws from this method. I think the worst a hacker could do is replicate Steps 3-5 and log you in to mydomain.com without you knowing, but that would be harmless.