我正在创建一个单向绑定(bind)指令,它有一个包含数组的属性,如下所示:
app.directive('interestBox', function() {
return {
restrict: 'E',
scope: {
interests: '@'
},
templateUrl: '/static/templates/directive_templates/interestbox.html',
link: function(scope, element, attrs) {
scope.interests = scope.$eval(scope.interests); //currently, doing this for converting string to array
console.log(scope.interests);
}
}
})
这是标记:
<interest-box interests="{{profile_data.interests}}">
</interest-box>
Controller :
$scope.profile_data.interests = [1, 2, 3, 4];
首先,我使用 @
而不是 =
的原因是我不需要 Controller 和指令之间的双向绑定(bind)(am我的这个假设正确吗?)
但是正如你所看到的,@
将当时的 DOM 值解析为字符串。现在,由于我的属性“interests”是一个数组,因此我需要将指令中的字符串(@
将其转换为字符串)转换为数组。为此,我正在做:
$scope.interests = scope.$eval(scope.interests);
这对我来说感觉不对。从字符串中获取数组的最佳方法是什么?
最佳答案
您希望在指令中拥有原始数组的副本以进行操作。修改数据准备好后,您可以使用隔离的本地数据更新原始 Controller 阵列。在你的情况下,它看起来像这样:
angular.module('demo', [])
.controller('DemoController', function($scope, $timeout) {
$scope.profile_data = {interests: [1,2,3]};
$timeout(function() {$scope.profile_data.interests.push(4);}, 1000);
})
.directive('interestBox', function($timeout, $parse) {
return {
restrict: 'E',
scope: {
interestsOrig: '=interests'
},
template: '<pre>{{ interests }}</pre><button ng-click="updateInterests()">Update controller array</button>',
link: function(scope, element, attrs) {
scope.interests = angular.copy(scope.interestsOrig);
// Modify interests, push new, remove old
$timeout(function() {
scope.interests.push(5);
scope.interests.splice(0, 1)
}, 2000);
// Update original controller interests with local
scope.updateInterests = function() {
scope.interestsOrig = scope.interests;
};
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<div ng-app="demo" ng-controller="DemoController">
<h4>Controller</h4>
<pre>{{ profile_data.interests }}</pre>
<h4>Directive</h4>
<interest-box interests="profile_data.interests"></interest-box>
</div>
关于javascript - AngularJS 指令 : parsing array from string in one way binding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33327998/