Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate ng-controller based on a condition

I asked this question but the specific question I'm asking has changed dramatically.

I have a piece of code:

  <div ng-attr-controller="{{pings || 'PingsCtrl as pings' }}">
    <h1 ng-click="pings.press()">asdf</h1>
  </div>

This code is injected into two html pages. One page already calls PingsCtrl. The other doesn't. I'm really trying to keep this code DRY and I only want to have one reference of the code above.

How can I write the code above to generate ng-controller if PingsCtrl hasn't already instantiated.

Here are the two html pages.

HTML

// First page
<html ng-app="coolApp">
  <div ng-controller="PingsCtrl as pings">
    <div ng-attr-controller="{{pings || 'PingsCtrl as pings' }}">
      <h1 ng-click="pings.press()">asdf</h1>
    </div>
  </div>
</html>

// Second page
<html ng-app="coolApp">
  <div ng-attr-controller="{{pings || 'PingsCtrl as pings' }}">
    <h1 ng-click="pings.press()">asdf</h1>
  </div>
</html>

Javascript is here:

angular.module('coolApp', [])

.controller('PingsCtrl', function() {
  var vm = this;

  vm.press = function() {alert(123)};
})

What's wrong and how do I fix this?

like image 875
thank_you Avatar asked Dec 21 '15 19:12

thank_you


1 Answers

Just use a service. It's really the intended structure for having common data and functionality between pages.

Part of the problem with what you were attempting is, whether or not you manage to preserve the controller, Angular has its own management that won't follow you with that, and will be refreshing components without you. You'll run into things like a $scope that doesn't actually match the page you're looking at, and it ends up causing more problems than it's worth.

like image 91
Harris Avatar answered Oct 19 '22 13:10

Harris