Simple Angular Directive within another Directive - how pass value to controller scope - javascript

Edit: I have added the details as well.
I could do with some help with passing the value selected in my directive to my controller $scope.
I have a very basic directive that I want to place within another directive, but the value does not get passed to the controller scope. I get an "undefined" value for my parameter.
However, when I place the little directive anywhere in the view's HTML, and not within the other directive's tags, it works.
This is my new directive:
(function () {
'use strict';
angular.module('portalDashboardApp')
.directive('ogItemsPerPage', function () {
return {
restrict: 'E',
replace: true,
templateUrl: './tpls/ItemsPerPageTemplate.html',
scope: {
perPageCountOptions: [30, 50, 100, "ALL"],
selectedItemsPerPage: '#'
}
};
});
})();
This is the template:
<div>
<div id="DropDownBox">
<label for="ItemsPerpage">Items per Page: </label>
<select ng-change="changePageCount()" ng-model="selectedItemsPerPage" id="ItemsPerpage" ng-options="perPage for perPage in perPageCountOptions"></select>
</div>
</div>
This is the function called in my controller:
$scope.changePageCount = function () {
if ($scope.selectedItemsPerPage === "ALL") {
$scope.perPageCount = -1;
}
else {
$scope.perPageCount = $scope.selectedItemsPerPage;
}
pullSocialData();
}
This is the view where I am placing my <og-items-per-page> directive, inside the tags of another directive:
<og-data-box heading="Tweet List" link="" uid="socialMentionsMeta" description="">
<div class="dataStatus">
{{dataStatus}}
<og-loading-indicator></og-loading-indicator>
</div>
<og-items-per-page></og-items-per-page>
<div class="dataContent" ng-show="dataContent" ng-mouseover="showGraphTrainingInfo()">
<og-social-media-mentions-list></og-social-media-mentions-list>
<div ng-show="showMorePostLoading" id="morePostLoadingContainer"><div id="morePostLoadingInner"></div></div>
</div>
</og-data-box>
The data-box directive:
(function () {
'use strict';
angular.module('portalDashboardApp')
.directive('ogDataBox', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
heading: '#',
link: '#',
uid: '#',
description: '#',
chartConfig: '#'
},
link: function (scope) {
scope.boxOpenCloseTitle = 'Collapse';
scope.iconStatus = 'upIcon';
scope.contentStatus = '';
var openCloseStatus = true;
var maximumSize = false;
scope.dataBoxUnderlayClass = '';
scope.dataBoxMaxMinClass = '';
scope.maxMinIcon = 'maximise';
scope.openCloseDataBox = function () {
if (openCloseStatus) {
scope.boxOpenCloseTitle = 'Expand';
openCloseStatus = false;
scope.iconStatus = 'downIcon';
scope.contentStatus = 'hideContent';
}
else {
scope.boxOpenCloseTitle = 'Collapse';
openCloseStatus = true;
scope.iconStatus = 'upIcon';
scope.contentStatus = '';
}
};
scope.maxMinDatabox = function () {
maximumSize = !maximumSize;
if (maximumSize) {
scope.dataBoxUnderlayClass = 'dataBoxUnderlayFullScreen';
scope.dataBoxMaxMinClass = 'dataBoxMaximised';
scope.maxMinIcon = 'minimise';
}
else {
scope.dataBoxUnderlayClass = '';
scope.dataBoxMaxMinClass = '';
scope.maxMinIcon = 'maximise';
}
};
},
templateUrl: './tpls/DataBoxTemplate.html'
};
});
})();
The data-box template:
<div ng-class="dataBoxUnderlayClass">
<section class="dataBox" id="{{uid}}" ng-class="dataBoxMaxMinClass">
<header class="dataBoxHeader">
{{heading}}
<img src="images/openCloseIcon.svg" title="{{boxOpenCloseTitle}}" width="15" height="15" class="openCloseBox {{iconStatus}}" ng-click="openCloseDataBox()" />
<img ng-mouseover="infoIconStyle='dataBoxInfoContentShow'" ng-mouseleave="infoIconStyle='dataBoxInfoContentHide'" src="images/info-icon.svg" height="15" class="dataBoxInfo" />
</header>
<div class="dataBoxContent {{contentStatus}}">
<div ng-class="infoIconStyle" class="dataBoxInfoContent">{{description}}</div>
<div ng-transclude></div>
</div>
</section>
</div>
What do I need to change so that I can nest my directive within other directives if I want to?
Thank you!

The problem comes from the isolated scope created by your directive.
The html inside og-data-box is under the directive scope and can't access to the controller scope.
As it is describe in this article http://angular-tips.com/blog/2014/03/transclusion-and-scopes/ if you want to access your controller scope inside <og-data-box></og-data-box> you need to append it to your isolated scope.
Something like that should correct your problem
app.directive('og-data-box', function() {
return {
restrict: 'EA',
scope: {
heading: '=',
link: '=',
uid: '=',
description: '='
},
transclude:true,
link: function(scope, element, attrs, ctrl, transclude) {
transclude(scope.$parent, function(clone, scope) {
element.append(clone);
});
}
};
});
EDIT :
As it is mentioned in the comment this is not the best way to do it.
You should pass your scope to the scope of og-data-box then you can use it in the nested directive :
og-data-box (I add selectedItemsPerPage to the scope)
(function () {
'use strict';
angular.module('portalDashboardApp')
.directive('ogDataBox', function () {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
heading: '#',
link: '#',
uid: '#',
description: '#',
chartConfig: '#',
selectedItemsPerPage: '#'
},
link: function (scope) {
scope.boxOpenCloseTitle = 'Collapse';
scope.iconStatus = 'upIcon';
scope.contentStatus = '';
var openCloseStatus = true;
var maximumSize = false;
scope.dataBoxUnderlayClass = '';
scope.dataBoxMaxMinClass = '';
scope.maxMinIcon = 'maximise';
scope.openCloseDataBox = function () {
if (openCloseStatus) {
scope.boxOpenCloseTitle = 'Expand';
openCloseStatus = false;
scope.iconStatus = 'downIcon';
scope.contentStatus = 'hideContent';
}
else {
scope.boxOpenCloseTitle = 'Collapse';
openCloseStatus = true;
scope.iconStatus = 'upIcon';
scope.contentStatus = '';
}
};
scope.maxMinDatabox = function () {
maximumSize = !maximumSize;
if (maximumSize) {
scope.dataBoxUnderlayClass = 'dataBoxUnderlayFullScreen';
scope.dataBoxMaxMinClass = 'dataBoxMaximised';
scope.maxMinIcon = 'minimise';
}
else {
scope.dataBoxUnderlayClass = '';
scope.dataBoxMaxMinClass = '';
scope.maxMinIcon = 'maximise';
}
};
},
templateUrl: './tpls/DataBoxTemplate.html'
};
});
})();
And then when you call all the directive :
<og-data-box heading="Tweet List" link="" uid="socialMentionsMeta" description="" selected-items-per-page="selectedItemsPerPage">
<div class="dataStatus">
{{dataStatus}}
<og-loading-indicator></og-loading-indicator>
</div>
<og-items-per-page selected-items-per-page="selectedItemsPerPage"></og-items-per-page>
<div class="dataContent" ng-show="dataContent" ng-mouseover="showGraphTrainingInfo()">
<og-social-media-mentions-list></og-social-media-mentions-list>
<div ng-show="showMorePostLoading" id="morePostLoadingContainer"><div id="morePostLoadingInner"></div></div>
</div>
</og-data-box>

Related

Angular - getting value from directive in the controller

I need to pass a selected value from a directive that I am using in several places. It is a select input field that I need to get a selected value from.
This is how the directive looks like:
angular.module('quiz.directives')
.directive('fancySelect', function($rootScope, $timeout) {
return {
restrict: 'E',
templateUrl: 'templates/directives/fancySelect.html',
scope: {
title: '#',
model: '=',
options: '=',
multiple: '=',
enable: '=',
onChange: '&',
class: '#'
},
link: function(scope) {
scope.showOptions = false;
scope.displayValues = [];
scope.$watch('enable', function(enable) {
if (!enable && scope.showOptions) {
scope.toggleShowOptions(false);
}
});
scope.toggleShowOptions = function(show) {
if (!scope.enable) {
return;
}
if (show === undefined) {
show = !scope.showOptions;
}
if (show) {
$rootScope.$broadcast('fancySelect:hideAll');
}
$timeout(function() {
scope.showOptions = show;
});
};
scope.toggleValue = function(value) {
if (!value) {
return;
}
if (!scope.multiple) {
scope.model = value;
console.log(scope.model);
return;
}
var index = scope.model.indexOf(value);
if (index >= 0) {
scope.model.splice(index, 1);
}
else {
scope.model.push(value);
}
if (scope.onChange) {
scope.onChange();
}
};
scope.getDisplayValues = function() {
if (!scope.options || !scope.model) {
return [];
}
if (!scope.multiple && scope.model) {
return scope.options.filter(function(opt) {
return opt.id == scope.model;
});
}
return scope.options.filter(function(opt) {
return scope.model.indexOf(opt.id) >= 0;
});
};
$rootScope.$on('fancySelect:hideAll', function() {
scope.showOptions = false;
});
}
};
});
When I do console.log(scope.model); I get the selected value, but I am not sure how to get it and use it in my controller?
This is the controller:
angular.module('quiz.controllers')
.controller('ProfileController', function(
$scope,
$state,
$stateParams,
UserService,
$auth,
MessageService,
$ionicLoading,
AppSettings,
$timeout,
AvatarService,
PushService,
$http
) {
$scope.user = UserService.get();
$scope.profilePromise = {};
if ($scope.user.player.avatar == ""){
$scope.user.player.avatar = AvatarService.getRandom();
}
$http.get(AppSettings.apiUrl + '/years')
.then(function(result) {
$scope.years = result.data;
});
$scope.updateUser = function(form) {
if (!form.$valid) {
var message = "Ugyldig data i skjema. Sjekk felter markert med rødt.";
MessageService.alertMessage(message);
return;
}
saveUser($scope.user);
};
$scope.getNextAvatar = function() {
$scope.user.player.avatar = AvatarService.getNext($scope.user.player.avatar);
};
$scope.getPreviousAvatar = function() {
$scope.user.player.avatar = AvatarService.getPrevious($scope.user.player.avatar);
};
var saveUser = function(user) {
$scope.profilePromise = UserService.save(user);
$scope.profilePromise.then(function(result) {
$scope.user = result.data.user;
PushService.init();
PushService.getDeviceId().then(function(id) {
UserService.addDevice(id);
});
if ($stateParams.register) {
$state.go('main.front');
}
}, function(error) {
var message = "Kunne ikke lagre bruker. Melding fra server: " + error.data.message;
MessageService.alertMessage(message);
});
};
});
You already have an onChange binding in the scope, so why don't you use that one?
In your directive:
if (scope.onChange) {
scope.onChange({ $value: scope.model });
}
Then pass a controller function to your directive:
<fancy-select on-change="onChange($value)"></fancy-select>
In your controller:
$scope.onChange = function(val) {
// do something with the value
}

Angular JS Directive params for change view

I have a directive and I need to give her a setting to change my view based on this parameter.
<ta-card type="unlock"
class="parent-card"
owner="currentUser"
ng-repeat="unlockCard in unlockedCards"
title="{{unlockCard.title}}">
</ta-card>
Here i send param title and i want recup here
<div class="card-footer">
<div class="card-info left floated">
<div class="info" ng-model="title"></div>
<span class="sub-info"
ng-if="$root.response==undefined">Chargement</span>
<span class="sub-info" translate="card.subtitle.soon_available" ng-if="$root.response!=undefined"></span>
</div>
<span class="flip-btn white"
ng-if="options.flip"
ng-click="flipCard(model.parentId != undefined)">
<i class="chevron right icon"></i></span>
</div>
</div>
Edit :
That's my directive, but i'm not sure that could be help you
.directive('taCard', ['appAuth', 'taCardService', '$rootScope', '$timeout',
function (appAuth, taCardService, $rootScope, $timeout) {
return {
restrict: 'E', // cards must be always an element, by convention
transclude: false,
replace: true,
scope: {
owner: '=?', //this is going to be an User Object
model: '=?',
readonly: '=?', //this makes form fields readonly,
transcludeData: '=?',
childLoad: '#',
unlockType: '#'
},
link: function (scope, element, attrs) {
// console.log(scope.model);
console.log(scope);
scope.showFront = true;
scope.displayChildCards = false;
scope.elementId = 'card-' + parseInt(Math.random() * 100000000000);
element.attr('id', scope.elementId);
scope.isEditable = false;
scope.options = taCardService.getOptions(attrs.type);
// console.log(scope.options);
scope.model = angular.isDefined(scope.model) ? scope.model : {};
if (scope.options.hasOwner) {
taCardService.hasAccess(scope.owner)
.then(function (access){
if (access === true) {
//set if is editable
appAuth.currentUser()
.then(function (currentUser) {
scope.currentUser = currentUser;
if (scope.owner.id === scope.currentUser.id) {
scope.isEditable = true;
}
});
} else {
// destroy the card if user doesn't have acccess
element.remove();
scope.$destroy();
}
});
}
if (taCardService.hasService(attrs.type)) {
taCardService.onLoad(attrs.type, scope, element);
taCardService.setEvents(attrs.type, scope);
scope.service = taCardService.getService(attrs.type);
}
// get the model data
if (taCardService.hasService(attrs.type)) {
taCardService.getModel(attrs.type, scope)
.then(function (data) {
scope.model.data = data.model;
},
function (error) {
console.log('impossible to get the model: status ' + error.status);
});
}
if (!angular.isDefined(scope.owner) && scope.options.hasOwner) {
// alert to the sleepy developer that must pass the owner
console.log('hey! you forgot the owner!');
return;
}
}
}
}
])
My factory
window.angular && (function(angular) {
'use strict';
angular.module('taApp')
.factory('taUnlockCard', ['$q','$rootScope', function($q,$rootScope) {
// JE RECUPERE LE TITRE DE LA CARTE ???
$rootScope.title="Titre";
return {
};
}]);
})(window.angular); // jshint ignore:line

Send an event using $emit from directive to controller

I'm trying to send an event when an item gets selected, from directive to controller using $emit. I've two update functions for organizations and another for people. My directive should specify which event should emit.
Here is my update functions:
// For organization
$scope.updateOrgs = function(selectedVal) {
}
// For people
$scope.updatepeople = function(selectedVal, type) {
}
When it is people my directive should raise an emit event for updatepeople (), if it was org it should raise updateorg().
My directive looks like:
.directive('search', function ($timeout) {
return {
restrict: 'AEC',
scope: {
model: '=',
searchobj: '#',
},
link: function (scope, elem, attrs, index) {
scope.handleSelection = function (selectedItem) {
scope.model = selectedItem;
scope.searchModel="";
scope.current = 0;
scope.selected = true;
$timeout(function () {
scope.onSelectupdate();
}, 200);
};
scope.Delete = function (index) {
scope.selectedIndex = index;
scope.delete({ index: index });
};
scope.Search = function (searchitem,event,searchobj) {
// alert('item entered'+name)
scope.searching = searchitem;
scope.searchobject = searchobj;
scope.onSearch({ searchitem: searchitem , searchobj:searchobj});
};
scope.current = 0;
scope.selected = true;
scope.isCurrent = function (index) {
return scope.current == index;
};
scope.setCurrent = function (index) {
scope.current = index;
};
},
controller: ['$scope','$element','$rootScope','SearchOrg', function($scope,$element,$rootScope,SearchOrg) {
$scope.searchItem = function(filter,searchobj){
//alert('search'+searchobj);
SearchOrg().fetch({'filter': filter, 'searchType': searchobj}).$promise.then(function(value){
$scope.searchData = value.data;
console.info($scope.searchData);
},
function(err) {
});
}
}],
templateUrl: TAPPLENT_CONFIG.HTML_ENDPOINT[0] + 'home/genericsearch.html'
}
});;
HTML snippet
<search searchobj=“tei-org” selectedItems=“arrayofIds” search-id=”someidtoIdentify”/>
How can I do this both functions are in different controllers, and also I need to send parameters from directive to the controller using $emit?
Working with $scope.$emit and $scope.$on
I'm guessing that your other controllers are not parents, so look at the second option using $broadcast.
var app = angular.module('app', []);
app.controller('firstController', function($scope) {
$scope.selectedOrgs = []
$scope.$on('updateorgs', function(evt, data) {
$scope.selectedOrgs.push(data);
});
});
app.controller('secondController', function($scope) {
$scope.selectedPeople = []
$scope.$on('updatepeople', function(evt, data) {
$scope.selectedPeople.push(data);
});
});
app.directive('someDirective', function($rootScope) {
return {
scope: {},
link: function(scope) {
scope.options = [{
id: 1,
label: 'org a',
type: 'org'
}, {
id: 2,
label: 'org b',
type: 'org'
}, {
id: 3,
label: 'person a',
type: 'person'
}, {
id: 4,
label: 'person b',
type: 'person'
}];
scope.changed = function() {
if (scope.selected) {
var updatetype = scope.selected.type;
if (updatetype === 'person') {
$rootScope.$broadcast('updatepeople', scope.selected);
} else if (updatetype === 'org') {
$rootScope.$broadcast('updateorgs', scope.selected);
}
}
};
},
template: '<select ng-change="changed()" ng-model="selected" ng-options="option.label for option in options"><option value="">Select</option></select>'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app'>
<some-directive></some-directive>
<div ng-controller='firstController'>
<div>ORGS:</div>
<div>
{{ selectedOrgs }}
</div>
</div>
<div ng-controller='secondController'>
<div>PEOPLE:</div>
<div>
{{ selectedPeople }}
</div>
</div>
</div>

AngularJS share data bettween parent and child scope directives

I have a widget like directive called waComments, it loads components via a RESTful service and displays them. In my view I'm using ng-repeat to loop over them and to render them with a button that if pressed Shows a new reply to form. This his handled by the waCommentsReply directive. One waComments widget has many child directives of type waCommentsReply. When the form is filled and submitted I want to add the new comment on top of my comments list. So both directives have to share the comments data.
I've tried to implement this here Sharing data between directives but without much success, the comment data is not updated when I add a new comment. I see that the RESTful API calls work and the data is returned, so this is not an issue.
Why is my implementation of Sharing data between directives not working in my case?
waCommentsReply directive:
waFrontend.directive('waCommentsReply', ['$rootScope', 'Comment', 'WaFormValidation', 'WaCommentStore', function($rootScope, Comment, WaFormValidation, WaCommentStore) {
return {
restrict: 'E',
templateUrl: '/stubs/comment-form.html',
transclude: true,
scope: {
replyTo: '#replyTo',
replyFormList: '=replyFormList',
loggedIn: '#loggedIn',
model: '#model',
id: '#id',
cancelButton: '#cancelButton'
},
controller: function($scope) {
$scope.comments = WaCommentStore;
if ($scope.cancelButton == undefined) {
$scope.cancelButton = true;
} else {
$scope.cancelButton = false;
}
$scope.comment = $scope.commentForm = {
Comment: {
author_name: '',
body: '',
model: $scope.model,
foreign_key: $scope.id,
parent_id: $scope.replyTo
}
};
$scope.$watch('replyFormList', function (newValue, oldValue) {
if (newValue) {
$scope.replyFormList = newValue;
}
});
if ($scope.loggedIn == undefined) {
$scope.loggedIn = false;
}
/**
* Handles the submission and response of a reply
*
* #return void
*/
$scope.reply = function() {
Comment.add($scope.comment).then(function(result) {
if (result.status == 'fail' || result.validation != undefined) {
$scope.validationErrors = result.validation;
WaFormValidation.validate(result.validation, $scope.commentForm);
} else if (result.status == 'success') {
//$scope.$parent.comments.unshift(result.data.comment);
//$scope.comments.unshift(result.data.comment);
$scope.comments.comments.unshift(result.data.comment);
//WaCommentStore.append($scope.model, $scope.id, result.data.comment);
$scope.comments, $scope.id, result.data.comment
$scope.comment = {};
$scope.replyFormList[$scope.replyTo] = false;
}
});
};
$scope.close = function() {
$scope.comment = {};
if ($scope.replyFormList[$scope.replyTo] != undefined) {
$scope.replyFormList[$scope.replyTo] = false;
}
}
}
};
}]);
WaCommentStore directive:
waFrontend.factory('WaCommentStore', function() {
return {
comments: []
};
});
waComments directive:
waFrontend.directive('waComments', ['$rootScope', 'Comment', 'WaCommentStore', function($rootScope, Comment, WaCommentStore) {
return {
restrict: 'E',
templateUrl: '/stubs/comments.html',
scope: {
model: '#commentModel',
id: '#commentFk'
},
controller: function($scope) {
$scope.comments = WaCommentStore;
$scope.loaded = false;
$scope.loadedMore = true;
$scope.currentPage = 1;
$scope.loggedIn = false;
$scope.paging = {};
$scope.replyFormList = {};
Comment.comments($scope.model, $scope.id).then(function(result) {
$scope.comments.comments.push.apply($scope.comments.comments, result.data.comments);
$scope.loggedIn = result.data.loggedIn;
$scope.paging = result.paging.Comment;
$scope.loaded = true;
});
$scope.loadMore = function() {
$scope.loadedMore = false;
if ($scope.paging.nextPage == false) {
//return false;
}
var options = {
page: $scope.paging.page + 1
};
Comment.comments($scope.model, $scope.id, options).then(function(result) {
$scope.comments.comments.push.apply($scope.comments.comments, result.data.comments);
$scope.paging = result.paging.Comment;
$scope.loadedMore = true;
});
};
$scope.submitComment = function() {
//alert($scope.author_name + $scope.body);
};
$scope.reply = function(replyId) {
$scope.replyFormList[replyId] = true;
}
}
};
}]);
since in both directive you defined scope: {} basically it means you defined those directives to use isolated scope.
with isolated scope, a scope/directive can't see what is in the parent scope.
however parent scope, can be affected by the child scope changes with 2 way binding definition.
https://docs.angularjs.org/guide/scope
try changing the shared data like this
waFrontend.factory('WaCommentStore', function() {
var comments = [];
var getComments = function() { return comments; }
var setComments = function(data) { comments = data; }
return {
getComments : getComments ,
setComments : setComments
};
});
I wanted to put it as a comments, but it would have been difficult to understand for you.
Please let me know if this works, else I will delete this answer.

why ng-click not working?

I write a directive to impl ng-disabled because i just can use angularjs which version is 1.1.5,it't not provide ng-disabled,so
tableApp.directive('myDisabled', function($compile) {
return {
restrict: 'A',
replace: true,
scope: {
myDisabled: '='
},
link: function(scope, element, attrs) {
var test = scope.$eval(attrs.myDisabled);
console.log(test);
scope.$watch(attrs.myDisabled, function (test) {
if (test) {
element.attr();
}
else {
element.attr('disabled', 'false');
}
});
}
};
});
the html code:
<html ng-app="tableApp">
<head></head>
<body>
<div ng-controller="TableCtrl">
<input ng-model="page"/>
<button class="btn btn-primary" ng-click="previouspage()" my-disabled="page <=1">上一页</button>
</div>
</body>
</html>
but why i click this button,it can't call the function previouspage()
this is my angularjs code
var tableApp = angular.module('tableApp', [], function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded;charset=utf-8';
});
tableApp.directive('myDisabled', function($compile) {
return {
restrict: 'A',
replace: true,
scope: {
myDisabled: '='
},
link: function(scope, element, attrs) {
var test = scope.$eval(attrs.myDisabled);
console.log(test);
scope.$watch(attrs.myDisabled, function (test) {
if (test) {
element.attr();
}
else {
element.attr('disabled', 'false');
}
});
$compile(attrs);
}
};
});
tableApp.controller('TableCtrl', function ($scope, $http) {
$scope.page = 1;
$scope.getCr = function getCr(later) {
var url = '/cms/copyright/find';
var request = $http({
method: 'get',
url: url,
params: {
page_length: 25,
start: ($scope.page - 1) * 25,
s: ''
}
});
request.then(function (data) {
if (data.data.result == 'OK') {
console.log(data.data);
$scope.copyright = data.data;
if (later != undefined) {
later();
}
}
});
};
$scope.nextpage = function nextpage() {
$scope.page += 1;
$scope.getCr();
};
$scope.onepage = function onepage() {
$scope.page = 1;
$scope.getCr();
};
$scope.previouspage = function previouspage() {
$scope.page -= 1;
$scope.getCr();
};
$scope.setPos = function setPos(index, holder_id) {
var pos = window.prompt("请输入排序位置", $scope.copyright.items[index].pos);
console.log(pos);
if (pos != null && pos != "" && parseInt(pos) > 0) {
var a = 'holder_id=' + holder_id + '&pos=' + pos;
$http.post('/cms/copyright/top', a).then(function (data) {
data = data.data;
if (data.result == 'OK') {
$scope.getCr(function () {
$scope.copyright.items[index].change = true;
});
} else {
alert(data.result);
}
});
}
console.log($scope.copyright.items[index]);
};
$scope.getCr();
});
Your problem is related to $scope.
When you are explicitly creating an isolated scope in your directive (using scope: {}) you can't access parent scope directly. If you don't, there is no problem doing so.
So, in short, just change ng-click="previouspage()" to ng-click="$parent.previouspage()" inside your HTML template.
Related plunker here: http://plnkr.co/edit/WRflPF
You could also refactor your directive's link function and remove unnecessary properties. So directive could be:
app.directive('myDisabled', function () {
return {
restrict: 'A',
scope: {
myDisabled: '='
},
link: function(scope, element) {
scope.$watch('myDisabled', function (val) {
element.attr('disabled', val);
});
}
};
});
The problem is the directive scope. You try to access an scope variable from parent scope (your controllers scope)
If you disable the isolate scope for your directive it works
For example:
tableApp.directive('myDisabled', function($compile) {
return {
restrict: 'A',
replace: true,
scope: {
myDisabled: '='
},
link: function(scope, element, attrs) {
var test = scope.$eval(attrs.myDisabled);
console.log(test);
scope.$watch(attrs.myDisabled, function (test) {
if (test) {
element.attr();
}
else {
element.attr('disabled', 'false');
}
});
}
};
});

Categories