Ole Albers Ole Albers - 1 year ago 117
AngularJS Question

Passing scope-variables to ng-include

I have a web form that contains the following two blocks:

<div class="mm-FilterRow">
<div>First Name:</div>
<div><i ng-hide="user.FirstName">Loading...</i><select ng-show="choices.FirstNames" ng-model="user.FirstName" ng-options="o as o for o in choices.FirstNames"></select></div>
<div class="mm-FilterRow">
<div>Last Name:</div>
<div><i ng-hide="user.LastName">Loading...</i><select ng-show="choices.LastNames" ng-model="user.LastName" ng-options="o as o for o in choices.LastNames"></select></div>

As you can see, the only difference between those two are the Scope-Variables "
and the selection options "

Because I have about 10 divs of the same structure I would like to do something like: (This is pseudocode, non-working)

<div ng-include="singlerow.html" caption="First name" scopetarget="user.FirstName" scopeSource="choices.FirstNames">
<div ng-include="singlerow.html" caption="Last name" scopetarget="user.LastName" scopeSource="choices.LastNames">

Is there a chance to achieve what I want? Or do I have to keep those ugly copy/paste-variants?

Answer Source

It's impossible, in this case better use directives.

angular.module('DirectiveExample', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.options = [1, 2, 3];
  $scope.field = "Test";
.directive('singlerow', function() {
  return {
    restrict: 'E',
    scope: {
      field: '=',
      options: '=',
    templateUrl: '/singlerow.html'
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="DirectiveExample">
<script type="text/ng-template" id="/singlerow.html">
  <div class="mm-FilterRow">
    <div>Last Name:</div>
    <div><i ng-hide="field">Loading...</i><select ng-show="options" ng-model="field" ng-options="o as o for o  in options"></select></div>

  <div ng-controller="Controller">
    <singlerow field="field" options="options"></singlerow>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download