0

I have a question that concerns conditional partial-a-like views in AngularJS. The example below isn't very optimal. It also returns an error that belongs to the line $compile(element.contents())(scope) that says that I can't use scope as a function - but otherwise it won't render everything correctly. The use case is as following:

  1. I'm requesting a Route over $http that returns a array of objects

  2. I'm ng-repeat that returned array of objects

  3. For every object (lets call it obj) a obj.view_edit value is given.

  4. If the obj.type equals plugin, a <plugin></plugin> directive is inserted

That would look like:

 <plugin view="content.view_edit"></plugin>

My Directive looks like:

 directive('plugin', function($compile) {
    var linker = function(scope, element, attrs) {
        console.log(scope.view);
        element.html(scope.view).show();
        $compile(element.contents())(scope);
    }
    return {
        restrict:"E",
        link: linker,
        scope: {
            view:'='
        }
    }
})

Do you have any better solutions?

1 Answer 1

1

You shouldn't need to do manual DOM manipulation in your link function to hide/show or $compiles until you're dealing with more complexity. Just use the native ng-if directive.

<div ng-repeat="obj in objects">
    <div ng-if="isPlugin(obj)">
        <plugin view="obj.view_edit"></plugin>
    </div>
    <div ng-if="!isPlugin(obj)">
        This is not a plugin.
    </div>
</div>

Then you would have a function in your scope that the ng-if references. This keeps the HTML cleaner and clear of as much logic as possible.

scope.isPlugin = function (obj) {
    return obj.type === 'plugin';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I managed this Problem using your approach with ngSwitch ng-switch="content.type" and a ng-switch-when="plugin" for every type.

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.