javascript - ng-click, scopes and nested directives in AngularJS -
javascript - ng-click, scopes and nested directives in AngularJS -
i have these nested directives inner of has 'x' sign, is, when clicked, supposed delete item (classic problem). basically, whole thing menu.
i have added ng-click 'x' sign/button of item, confused on how link whole thing controller, can phone call deleteitem() function , remove item. want have scope sidebar-item separated (the original version of code more elaborated , has conditional statements)
here's have far total working - i.e. not working - version can found in jsfiddle
here's relevant part of html:
<div ng-app="demoapp"> <div ng-controller="sidebarcontroller"> <div sidebar> <div sidebar-item ng-repeat="item in items" item="item"></div> </div> <button ng-click="additem();">add item</button> </div> </div>
and here's javascript:
var demoapp = angular.module('demoapp', []); demoapp.controller("sidebarcontroller", ["$scope", function($scope) { $scope.items = [ ]; $scope.itemid = 1; $scope.additem = function() { var inx = $scope.itemid++; $scope.items.push( { id: inx, title: "item " + inx, subtitle: "extra content " + inx } ); }; $scope.deleteitem = function(item) { console.log("delete this!"); console.log(item); }; }]); demoapp.directive("sidebar", function() { homecoming { restrict: "a", transclude: true, template: '<div><div ng-transclude></div></div>', controller: ["$scope", function($scope) { this.deleteitem = function(item) { $scope.deleteitem(item); $scope.$apply(); }; }] }; }); demoapp.directive("sidebaritem", function() { homecoming { restrict: "a", scope: { item: "=" }, require: "^sidebar", template: '<div><span>{{ item.title }}</span><br /><span>{{ item.subtitle }}</span><br /><span ng-click="deleteitem(item)">x</span></div>', }; });
im sure reply simple, cant find it.
if want utilize required controller function need inject link function
in sidebar-item
add
link : function (scope, element, attrs, sidebar) { scope.deleteitem = function (item) { sidebar.deleteitem(item); } }
javascript angularjs angularjs-directive angularjs-scope
Comments
Post a Comment