Abhishek Asthana Abhishek Asthana - 1 year ago 96
AngularJS Question

call function in controller from template.html

I am new to AngularJS, Somehow while going through many sites now I am able to create a directive for showing some data.Now I need to send some data to controller by clicking the button. I need to know the proper way of doing this

I have created the plunk


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

<script data-require="jquery@*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>

<body ng-controller="movieDesc">
<div ng-repeat="m in movies" movies="m"></div>


Directive and Controller

// Code goes here

angular.module('app', []);

angular.module('app').controller('movieDesc', function($scope) {

$scope.movies = [{
name: 'abc',
desc: 'this is desc text for the movie',
pic: 'http://png.clipart.me/graphics/thumbs/134/abstract-geometric-background-triangle-and-square-black_134053397.jpg'
}, {
name: 'def',
desc: 'this is desc text for the movie def',
pic: 'http://png.clipart.me/graphics/thumbs/201/abstract-modern-banner-background-of-geometric-shapes-abstract-geometric-form_201768245.jpg'
}, {
name: 'ghi',
desc: 'this is desc text for the movie ghi',
pic: 'http://www.cianellistudios.com/images/abstract-art/abstract-art-infinite-150.jpg'

$scope.saveData = function(data) {


angular.module('app').directive('movies', function() {
return {
templateUrl: "movieCard.html",
restrict: "EA",
scope: {
movies: '='
link: function(scope, element, attrs) {
var clickedFn = function() {
console.log("console", element[0].querySelector('.btnSelect'));
var $this = element[0].querySelector('.btnSelect');
$($this).click(function() {




My Template

<b>Name:</b> {{movies.name}}
<b>Description:</b> {{movies.desc}}
<img src="{{movies.pic}}" />
<input type="text" ng-model="movies.someText">
<input class="btnSelect" type="button" value="Desc" ng-click="clickedFn()">
<input class="btnSelect" type="button" value="Save Data" ng-click="saveData({{movies}})">

I need to send the data to the controller's
function, the data will be entered through the textbox. I have given it as
which I suppose is the wrong way.

So please help me.

Answer Source

Use the & scope binding.

scope: {
    movies: '=',
    save: '&'

and in the directive template

<input type="button" ng-click="save({movie: movies})" ...>

You then bind the controller method via

<div ng-repeat="m in movies" movies="m" save="saveData(movie)"></div>

Note the argument name passed to the controller function matches the object key in the directive template.


While you're there, use ng-src instead of src to avoid a 404 request for a non-existent image

<img ng-src="{{movies.pic}}" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download