Angular在自定义指令中设置新变量

时间:2016-04-08 08:42:39

标签: javascript angularjs angularjs-directive

我正在学习Angular课程,作为一个完整的新手,我有一个新手问题,询问自定义指令。我想知道我们如何在自定义指令中设置新变量并在我们的视图中访问它们,如果有人能够以明确的方式解释它,那么这是否可能?

例如:

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {

$scope.person = {
    name: 'John Doe',
    address: '555 Main St., New York, NY 11111'
}

}]);

myApp.directive("searchResult", function() {
return {
   restrict: 'AECM',
   templateUrl: 'directives/searchresult.html',
   replace: true,
   scope: {
       personName: "@",
       personAddress: "@",
       newVariable: "someValue"
   }
 }
});

searchresult.html

<a href="#" class="list-group-item">
<h4 class="list-group-item-heading">{{ personName }}</h4>
<p class="list-group-item-text">
    {{ personAddress }}
</p>
<p class="list-group-item-text">
    {{ newVariable }}
</p>

main.html中

<label>Search</label>
<input type="text" value="Doe" />
 <h3>Search Results</h3>
<div class="list-group">
<search-result person-name="{{ person.name }}" person-address="{{ person.address }}" newVariable="{}"></search-result>

2 个答案:

答案 0 :(得分:1)

link function用于本地scope

myApp.directive("searchResult", function() {
return {
   restrict: 'AECM',
   templateUrl: 'directives/searchresult.html',
   replace: true,
   scope: {
       personName: "@",
       personAddress: "@"
   },
   link: function(scope, elem, attr) { scope.newVariable='something'; },
 };
});

答案 1 :(得分:0)

Use This. 

       var app = angular.module("test",[]);
       app.controller("Ctrl1",function($scope){    $scope.name = "Abc";    $scope.reverseName = function(){
       $scope.name = $scope.name.split('').reverse().join('');    }; });

 app.directive("myDirective", function(){    return {
       restrict: "EA",
       scope: false,
       template: "<div>Your name is : {{name}}</div>"+
       "Change your name : <input type='`enter code here`text' ng-model='name' />"    }; });