0

我有,看起來像如何訪問我的指令模板中的ng-model值?

<!-- selectList.tpl.html --> 
<div ng-if="selectList"> 
    <p>Id: {{$id}}</p> 
    <p>Current list item {{currentItem}}</p> 
    <select ng-model="currentItem" 
    name="current-item" 
    ng-options="item as item.value group by item.group for item in selectList"> 
    <option value="">All</option> 
    </select> 
</div> 

我想從我向鏈路函數內部訪問currentItem值來創建一個表函數,即模板的指令,

app.directive('selectList', [ 
    "$rootScope", 
    "$timeout", 
    function (
    $rootScope, 
    $timeout 
) { 
    "use strict"; 

    var getList = function() { 
     // ... 
    }; 

    return { 
     restrict: 'E', 
     templateUrl: 'selectList.tpl.html', 
     link: function(scope, element, attrs) { 
     scope.selectList = getList(); 
     scope.currentItem = ""; 

     console.log("scope id:", scope.$id); 

     scope.$watch('currentItem', function(item) { 
      $timeout(function() { 
      console.log("currentItem is", item); 
      angular.element("#console").append("<p>Updated item: " + item + "</p>"); 
      }); 
     }); 
     } 
    }; 
    } 
} 

然而,在scopecope下創建一個子範圍,用於存儲對選擇框值的更改。如何訪問我的指令鏈接代碼中的選擇框更改?

我正在使用Angular 1.1.5。

這是問題的一個plunker(已在Q更新的代碼,以反映plunker):http://plnkr.co/edit/5eOaRE?p=preview

+0

如果你有幾分鐘的時間,你可以設置一個plunkr嗎? – eddiec

+1

很難說出你在什麼範圍內玩遊戲而沒有顯示指令代碼 – charlietfl

+0

已添加plunker – zlog

回答

1

ng-if正在創建另一個範圍。因此,當您更新子作用域中的值時,它不會更新父作用域。

查看更新後的plunker:http://plnkr.co/edit/3sXPZmhkOJd5uhMJkICx?p=preview

如果你需要保持NG-如果你需要調用從子作用域父範圍內定義的函數。

+0

啊,就是這樣!我沒有額外的'scope'指令屬性就可以工作:http://plnkr.co/edit/uJBzuv?p=preview – zlog

0

可以聲明在指令中的範圍和建立雙向與屬性結合。例如:

<my-directive attr="myVal"> 

myApp.directive('myDirective', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      attr: '=', 
     }, 
     template: '<select ng-model="attr"> ... </select>', 
     replace: true 
    }; 
}); 

理論上你應該可以直接使用ng-model,但是我遇到了麻煩。如果在範圍中聲明的屬性名稱和變量名稱相同,則可以按照我在示例中編寫的方式使用範圍。否則,你將不得不更具體。

+0

下面是我在plunker中的內容:http://plnkr.co/edit/5mzGVF?p=preview - 雖然不起作用。 – zlog

相關問題