2015-10-13 3 views
0

Я читал через некоторые документы и книги о Угловом, но я на самом деле не найти угловой путь следующей задачи:Как «привязать» HTML-представление к контроллеру

Если у меня есть контроллер (допустим, CardController) и еще один контроллер, который обрабатывает создание нескольких экземпляров CardController. Как мне реализовать HTML-материал? Я хочу иметь возможность создать экземпляр Card, который имеет определенный HTML-код (например, тот, который приведен ниже) и подключен к CardController.

Я не думаю, что я должен загрязнять CardController, чтобы настроить HTML-материал с уродливым .append -материалом. Или это так? Должен ли я написать дополнительную услугу для представления HTML, например CardView, или создать дополнительную директиву?

Если вы посмотрите на этот пример, я хочу, чтобы иметь возможность нажать на кнопку «Добавить еще одну карту» и увидеть еще один экземпляр карты добавлен ниже (так в основном возможность иметь несколько элементов):

<!DOCTYPE html> 
 
<html ng-app="theApp"> 
 

 
<head> 
 
    <script data-require="[email protected]" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script> 
 
</head> 
 

 
<body> 
 

 
    <div ng-controller="MainController"> 
 
    <button ng-click="add()">Add another card</button> 
 
    </div> 
 

 
    <div id="content"> 
 
    <div ng-controller="CardController"> 
 
     <h1>{{ title }}</h1> 
 
     <p>{{ message }}</p> 
 
    </div> 
 
    </div> 
 

 
    <script> 
 
    (function() { 
 
     var app = angular.module("theApp", []); 
 

 
     app.controller('MainController', function($scope) { 
 
     $scope.add = function() { 
 
      // Setup HTML for TheController: 
 
      // add another DIV/H1/P-etc. to #content, 
 
      // just like the one at the beginning. 
 
      console.log("Add another card"); 
 
     }; 
 
     }); 
 

 
     app.controller('CardController', function($scope) { 
 
     $scope.title = "A Title"; 
 
     $scope.message = "Some message"; 
 
     }); 
 

 
    }()); 
 
    </script> 
 

 
</body> 
 

 
</html>

+0

Вы проверили директивы? Вы можете указать тег со свойствами, которые вы хотите. –

ответ

2

Попробуйте этот код из моего фрагмента кода:

(function() { 
 
    var app = angular.module("theApp", []); 
 

 
    app.controller('MainController', function($scope) { 
 
    var iter = 1; 
 
    $scope.cards = [{ 
 
     id: 1 
 
    }]; 
 

 
    $scope.add = function() { 
 
     $scope.cards.push({ 
 
     id: ++iter 
 
     }); 
 

 
     // Setup HTML for TheController: 
 
     // add another DIV/H1/P-etc. to #content, 
 
     // just like the one at the beginning. 
 
     console.log("Add another card"); 
 
    }; 
 
    }); 
 

 
    app.controller('CardController', function($scope) { 
 
    $scope.title = "A Title"; 
 
    $scope.message = "Some message"; 
 
    }); 
 
}());
<!DOCTYPE html> 
 
<html ng-app="theApp"> 
 

 
<head> 
 
    <script data-require="[email protected]" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script> 
 
</head> 
 

 
<body ng-controller="MainController"> 
 

 
    <div> 
 
    <button ng-click="add()">Add another card</button> 
 
    </div> 
 

 
    <div id="content"> 
 
    <div ng-repeat="card in cards" ng-controller="CardController"> 
 
     <h1>{{ title }}</h1> 
 
     <p>{{ message }}</p> 
 
    </div> 
 
    </div> 
 

 
</body> 
 

 
</html>

+0

Ничего себе, это умно! Я не думал об использовании 'ng-repeat' и списка (который может быть пустым без жалобы). – tamasgal

+0

Есть ли способ получить доступ к '$ scope'' карт' в 'MainController'? – tamasgal

0

один подход

<div ng-repeat="test in tests>{{test}}</div> 

$scope.tests = ["Test Message","Test Message 2"]; 
$scope.tests.push("new msg"); 

это Вл автоматически создать DIV и ур список растет

или

http://blog.sodhanalibrary.com/2014/08/append-or-prepend-html-to-div-using.html#.Vhz-NxOqqko

+0

Это не работает, потому что 'MainController' не завершает div с id' content' – Niezborala

2

Существует несколько вариантов. Например, вы можете использовать угловые директивы (для меня это самое элегантное решение) и создать HTML-структуру, как это:

<div ng-controller="MainController"> 
    <button ng-click="add()">Add another card</button> 

    <div id="content"> 
     <your-card-directive ng-repeat="card in cards" card-data="card"></your-card-directive> 
    </div> 
</div> 

или использование нг-включить, чтобы загрузить HTML из ваших HTML файлов:

<div ng-controller="MainController"> 
    <button ng-click="add()">Add another card</button> 

    <div ng-repeat="card in cards" ng-controller="CardController as CardCtrl" ng-include="'../../your-card-template.html'"></div> 
</div> 

или просто использовать встроенный HTML:

<div ng-controller="MainController"> 
    <button ng-click="add()">Add another card</button> 

    <div ng-repeat="card in cards" ng-controller="CardController"> 
     <h1>{{ title }}</h1> 
     <p>{{ message }}</p> 
    </div> 
</div> 
Смежные вопросы