AngularJS - Change controller by condition?

后端 未结 3 468
渐次进展
渐次进展 2021-01-24 19:21

I have a simple form with data which summarize the pressed items ( via addition)

(JSBIN)

\

3条回答
  •  猫巷女王i
    2021-01-24 19:47

    There doesn't seem to be a built-in way to choose a controller based on some condition. The ngController directive doesn't seem to play well with interpolation of the name via {{ }}, or passing a string version of the controller name, so it doesn't seem to be possible to choose a controller by ngController dynamically based on some condition in the scope.

    The most flexible solution to this I think is writing a custom directive, that accepts a string variable (including one returned by an expression)

    Inside {{name}}

    That then takes the name of the controller, puts it in an ng-controller attribute, and then (re)compiles the element, and do this whenever the expression returned by dynamic-controller changes. This could be done as follows:

    app.directive('dynamicController', function($compile) {
      return  {
        transclude: 'element',
        scope: {
          'dynamicController': '=' 
        },
        link: function(scope, element, attr, ctrl, transclude) {
          var el = null;
          scope.$watch('dynamicController',function() {
            if (el) {
              el.remove();
              el = null;
            }
            transclude(function(clone) {
              clone.attr('ng-controller', scope.dynamicController);
              clone.removeAttr('dynamic-controller');
              el = $compile(clone[0])(scope.$parent)
              element.after(el);
            });
          });
        }
      }
    });
    

    You can see this in action in this Plunker

提交回复
热议问题